Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 connection string for entity framework 4.1 code first

I need a valid SQL Server 2008 connection string for Entity Framework 4.1 code-first project. I would use it now with MVC 3.

For now it's still very simple, only 1 project, 3 simple model class...

I could only find everything else, like Sql Express, CE connections on the web...

Finding it by name in web.config ("ApplicationServices") is OK, because when I tried to use I got specific errors for that.

The best I could get is:

Unable to load the specified metadata resource.

I tried to give it like metadata=res://MyWebProject/MyWebProject.csdl| ... also but no success.

So it doesn't create the database for me - even doesn't hit the OnModelCreating(DbModelBuilder modelBuilder) method.

If I try to use an 'old fashioned' connection like the ones I found for SQL Server Express, it misses the metadata.

Thanks for your help in advance.

like image 428
DavidR Avatar asked Jul 04 '11 20:07

DavidR


People also ask

How do I change the connection string in Entity Framework?

If you want to change the connection string go to the app. config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.


1 Answers

The idea of "Code-First" is, that you shouldn't have to deal with the .csdl, .ssdl and .msl files mentioned in the connection-string. If not specified elsewhere, the DbContext will lookup the connection-string in the web.config as you described. The constructor of the DbContext class will accept a name-value pair specifiying the name of the connection-string in the web.config. For example:

<connectionStrings>
    <add name="ConnectionName" 
         providerName="System.Data.SqlClient"
         connectionString="Server=ServerName;Database=DatabaseName;Integrated Security=True;" />
</connectionStrings>

can be referenced in your context:

class MyContext : DbContext
{
     public MyContext() : base("name=ConnectionName") { }
     ...
}

The sample connection-string I've provided is actually for a SQL Server database. It is important to specify the ProviderName, since the "Code-First" requires it to generate a corresponding .ssdl-File (storage schema).

like image 200
J. Tihon Avatar answered Oct 19 '22 16:10

J. Tihon