How to Connect to SQL Server 2008 R2 Using EF and MVC 3

▼魔方 西西 提交于 2019-12-04 20:47:26

By default, EFCF will try to make a database from your model on your local ./SQLEXPRESS If you want to specify a different connection string in your web.config you have to tell EF the name of your connection string in the constructor of your database context like below:

public class MvcMusicStoreContext: DbContext 
{
    //Add the name of your database connection to the base DbContext calss
    public MvcMusicStoreContext() : base("MusicStoreDB")
    {}

    public DbSet<Album> Albums { get; set; }

    public DbSet<Genre> Genres { get; set; }

    public DbSet<Artist> Artists { get; set; }
}

Your connection string:

<add name="MusicStoreDB" connectionString="Data Source=localhost;Initial Catalog=MusicStoreDB;Integrated Security=True" providerName="System.Data.SqlClient"/>
basha

just replace your conn string with this and if you have copied MvcMusicStore.mdf files delete those from App_Data folder hope it will work

<clear />

<add name="MusicStoreEntities" connectionString="data source=.\SQLEXPRESS1;Integrated Security=SSPI;Initial Catalog=MvcMusicStore;AttachDBFilename=|DataDirectory|MvcMusicStore.mdf;User Instance=true" providerName="System.Data.SqlClient" />

Your connection string for EF needs to be an EntityConnection Connection String.

Check your app.config in the project where you created the Entity Framework edmx (if you used a database to create the model), and a connection string should be in there.

Here is some sample code to create the EF Connection String:

efName is the name of your edmx file. Example: Test.edmx - efName = "Test"

    private static string GetEntityFrameworkConnectionString(string connectionString, string efName)
    {
        var entityBuilder = new EntityConnectionStringBuilder();
        entityBuilder.Provider = "System.Data.SqlClient";
        entityBuilder.ProviderConnectionString = connectionString;
        entityBuilder.Metadata = "res://*/" + efName + ".csdl|res://*/" + efName + ".ssdl|res://*/" + efName + ".msl";
        return entityBuilder.ToString();
    }

For SQL Server 2008 R2 Developer Edition you can use the following connection stirng for your pc
<add name="MvcMusicStoreContext" connectionString="Data Source=MVC3Machine; Initial Catalog=MusicStoreDB; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!