13

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.

2 Answers 2

34

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).

Sign up to request clarification or add additional context in comments.

1 Comment

If the database schema does not exist and I am using sql server 2008, will the agent automatically create the database?
3

Besides, you can name your connection string after your DbContext class. In this case you may not mention the name of the connection string

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

and the connection string is the folowing

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.