该模型支持的<数据库>背景已经改变,因为在创建数据库。 [英] The model backing the <Database> context has changed since the database was created.

查看:197
本文介绍了该模型支持的<数据库>背景已经改变,因为在创建数据库。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该错误消息:

的模式支持的地址簿背景已经改变,因为在创建数据库。手动删除/更新数据库,或拨打Database.SetInitializer与IDatabaseInitializer实例。例如,RecreateDatabaseIfModelChanges战略将自动删除并重新创建数据库,以及可选的种子用新的数据。

"The model backing the 'AddressBook' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."

我想用code-第一特征,下面是我写的:

I am trying to use the code-first feature and following is what I wrote:

var modelBuilder = new ModelBuilder();
            var model = modelBuilder.CreateModel();
            using (AddressBook context = new AddressBook(model))
            {
                var contact = new Contact
                {
                    ContactID = 10000,
                    FirstName = "Brian",
                    LastName = "Lara",
                    ModifiedDate = DateTime.Now,
                    AddDate = DateTime.Now,
                    Title = "Mr."

                };
                context.contacts.Add(contact);
                int result = context.SaveChanges();
                Console.WriteLine("Result :- "+ result.ToString());

            }

上下文类:

public class AddressBook : DbContext
    {
        public AddressBook()
        { }
        public AddressBook(DbModel AddressBook)
            : base(AddressBook)
        {

        }
        public DbSet<Contact> contacts { get; set; }
        public DbSet<Address> Addresses { get; set; }
    }

和连接字符串:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
    <add name="AddressBook" providerName="System.Data.SqlClient"  
         connectionString="Data Source=MyMachine;Initial Catalog=AddressBook;
         Integrated Security=True;MultipleActiveResultSets=True;"/>
    </connectionStrings>
</configuration>

所以,数据库名称为通讯录,当我试图接触对象添加到上下文中的错误发生。我缺少什么吗?

So, the database name is "AddressBook" and the error happens when I trying to add the contact object to the context. Am I missing anything here?

推荐答案

刚刚发现更新这里的答案和想法。只需要做到以下几点。

Just found out the answer and thought of updating here. Just need to do the following.

public class AddressBook: DbContext
{
   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
    modelBuilder.IncludeMetadataInDatabase = false;
   }
}

这篇关于该模型支持的&lt;数据库&GT;背景已经改变,因为在创建数据库。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆