I'm getting the Unable to create object context error when using Entity framework in ASP.NET MVC.
Background
Every time I POST to the controller I'm not getting a response back. I tried going directly to the method of the controller /Data/GetAll, and receive this error:
Error
The specified named connection is
either not found in the configuration,
not intended to be used with the
EntityClient provider, or not valid.
Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.
Exception Details:
System.ArgumentException: The
specified named connection is either
not found in the configuration, not
intended to be used with the
EntityClient provider, or not valid.
Code Snippet that throws exception:
public class TrackItContextCreator {
public ObjectContext Create() {
ObjectContext context = new ObjectContext("name=TrackItDBEntities");
context.DefaultContainerName = "TrackItDBEntities";
return context;
}
}
Web.config
<add name="TrackItDBEntities" connectionString="metadata=res://*
/EntityFramework.TrackItDBModel.csdl|res://*/EntityFramework.TrackItDBModel.ssdl|res:
//*/EntityFramework.TrackItDBModel.msl;provider=System.Data.SqlClient;provider
connection string="Data Source=host;User ID=myuseracc;Password=******;
MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
What could I be missing?
From the comments, I think I know what the problem is.
If the model is in a separate assembly, you basically have to make sure that the connection string is specified in the app.config/web.config of every assembly that uses the model. I'm guessing that you only have it in the model project.
See this question for another example, and this thread on MSDN. Both similar issues involving models being in separate projects/assemblies. I'm 99% sure that this is related to your issue.
If you develop web app with class libarary you should add databases' connectionStrings to both of Web.Config and App.Config.
Related
I have a Windows Azure Mobile Services app that has a Code First generated database. The connection string (for when run locally) looks like this:
<add name="MS_TableConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\<database_name.mdf;Initial Catalog=<database_name>;Integrated Security=True;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
I created a new Console App project, referencing the Mobile Services project, and copied this connection string to the App.config file
In Program.Main() I created a new instance of the Context class from the Designer in the Mobile Services project. But when I run the Console App, and try to access one of the DbSets made public by the Context, I get the following exception:
"An exception occurred while initializing the database. See the InnerException for details."
With an inner exception of:
"The underlying provider failed on Open."
Which in turn has an inner exception of:
"Cannot attach the file 'C:\\...\\<database_name>.mdf' as database '<database_name>'."
If I remove the AttachDbFilename part of the connection string in the Console App, I get the following exception at the same point in the code:
"Cannot create more than one clustered index on table 'dbo.<Table_Name>'. Drop the existing clustered index 'PK_dbo.<Table_Name>' before creating another"
Does anyone have any idea why it would be trying to create this new clustered index when there already appears to be one?
Or any ideas what connection string I should use just to get a normal read/write connection to the database without it doing anything weird? Is this related to database initialization?
Edit: I've had a bit more of a play around with this, this morning. I can get it working without exceptions if I remove the inheritance of "Microsoft.WindowsAzure.Mobile.Service.EntityData" from my model classes, so this appears to be pretty significant.
Ok I've just battled through this and got it working. Gonna type this up in case it helps anyone one day.
So the problem is something to do with the fact that my Code First model classes were inheriting from EntityData. As I said in my edit above, removing this inheritance does appear to fix the problem. I think this is because the EntityData class has both a property with a [Key] attribute and a separate property with a [Index(IsClustered = true)] attribute. Because you can't have more than one Clustered Index in a table, the database initialization fails. In the default Azure Mobile Services project, there must be some magic that means this doesn't happen somewhere - but from a separate project you get the "Cannot create more than one clustered index on table" exception.
So what I did was disable Database Initialization in the separate Console App by adding the line:
Database.SetInitializer<MobileServiceContext>(null);
...before the DbContext is instantiated.
This allows me to use the database initialized by the Mobile Services App as an existing database, without attempting to make any changes to it.
I also needed the following AppSetting in the config file of the Console App, in order for it to use the correct Schema Name:
<add key="MS_MobileServiceName" value="<CorrectSchemaName>" />
The problem is that the web page was not deployed after migrating using another computer and also, the migration file was deleted.
the error was
The model backing the 'ProjectContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The model backing
the 'ProjectContext' context has changed since the database was
created. Consider using Code First Migrations to update the database
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
is there any way to solve this problem from my computer? or there is another problem behind this?
What the message says is that your database model is out of sync with your Entity Framework 'Code First' model / code.
To overcome this issue, you can use Code First Migrations. The linked tutorial on MSDN explains what you should do. You effectively have to use the Package Console and some C# code to migrate one version to another. This is something you have to do while coding the project. If you release it, the code can automatically update your database model to match your Entity Framework Code First code.
Can please some tell me when does the above written error occurs. I just wanted to get more information on this.
Check the config file where you mentioned the connection string and correct it...
The database mentioned might not be a valid one, or the server name might not be valid.
Your connection string should look like this
Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;
Place your connection string to the host library or the start up project.
It is clear that you are trying to access the config entry and it is not found thus this error thrown by the Configuration Manager/accessor.
Give us some code to diagnose the issue its hard to guess what causing the error.
I have an EntityFramework project running off MySql that runs great locally as well as on a dedicated server, however I'm trying to move this project to HostGator and I'm receiving the following error:
Schema specified is not valid. Errors:
App_Code.WireWeld.ssdl(2,88) : error 0002: Request failed.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.MetadataException: Schema specified is not valid. Errors:
App_Code.WireWeld.ssdl(2,88) : error 0002: Request failed.
I know the database is correct as I can connect via Navicat and see its contents. I'm pretty sure the connection string is correct, I have the proper username and password.
I'm really stuck on this one and would appreciate any help possible.
If you are using more than one model in your project I advice you to have a look into that topic as it describes possible solutions to the problem.
If you are not using multiple models than this looks like a file permission issue to me.
Perhaps in the hosted environment, the account underwhich your application is running doesn't have access to where the metadata files are located?
You should make sure you have permission (read/write are required). If this is not an option for you than the only go would be to embed the metadata in the assembly directly and use a res:// style connection string.
If you're using SQL server and have 2 projects - one is a class library and the 2nd one uses that class library in main project, then place both dll from class library project to main project refrence.
1-EntityFramework.dll
2-EntityFramework.SqlServer.dll
I have a database and a C# class library which acts as a repository for accessing objects from the database using Entity Framework. When trying to use this repository assembly in other projects I am running into difficulty; My working assumption is that this it due to the Connection String as I am getting the following error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
I have added an App1.config file to the project and added the same connection string I had successfully used when creating the database:
<add name="EDSEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SQLite;provider connection string='data source="C:\Documents and Settings\hmay\My Documents\My Projects\Timetabler\DataSets\EDS.db";foreign keys=true'" providerName="System.Data.EntityClient" />
.... but it doesn't work. I don't understand the connection string very well and wondered if there is something else here I might need to tweak?
Regards
Adding app1.config would not do anything. App.config and web.config are specially named files and they need to be named exactly that. However if you use your library in multiple apps i would refactor it.
Change the DbContext class to have a single constructor that takes a connection string and push the responsibility for creating the connection string into the app rather than the library. It is not good to have a class library that expects your app to have a particular named entry in the connection strings section of its config.
try trimming metadata references to metadata=res://*