Second database created with MVC3, how to prevent?

╄→гoц情女王★ 提交于 2019-12-05 16:46:55

It's because the connectionString that you have didnt find the file for your database so CodeFirst create one automaticaly by using the full namespace of where your DbContext is for the filename.

Insert this text in the connectionString by changing the filename.mdf by the filename that you want: AttachDBFilename=|DataDirectory|filename.mdf. The database file will be in your project\App_Data folder.

you will have something like this:

<connectionStrings>
    <add name="RecettesMaison" connectionString="Data Source=.\SQLEXPRESS;Initial catalog=RecettesMaison;AttachDBFilename=|DataDirectory|filename.mdf;User Id=user;Password=password;" providerName="System.Data.SqlClient"/>
</connectionStrings>

Be sure that your DbContext is using the right connectionString by passing the connectionStringName in the DbContext constructor like this:

public class RecettesMaisonContext : DbContext
{
    public RecettesMaisonContext()
        : base("RecettesMaison")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var typesToRegister =
            Assembly.GetExecutingAssembly().GetTypes().Where(
                type =>
                type.BaseType.IsGenericType &&
                type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

        foreach (object configurationInstance in typesToRegister.Select(Activator.CreateInstance))
        {
            modelBuilder.Configurations.Add((dynamic)configurationInstance);
        }
    }

    ...
}

By default, code first will create a DB for you. If you however want to override this behaviour just use

Database.SetInitializer<YourDataContext>(null);

MSDN: msdn.microsoft.com/en-us/library/gg679461(v=vs.103).aspx

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