The model backing the 'ProductContext' context has changed since the database was created. EF6

学习《Entity Framework 6 Recipes 2nd Edition》,2-6. Splitting an Entity Among Multiple Tables中遇到几个问题

表结构:

操作

1.构造数据对象

public class Product
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int SKU { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public string ImageURL { get; set; }
    }

2.构造DBContext

public class ProductContext:DbContext
    {
        public DbSet<Product> Products { get; set; }
        public ProductContext()
            : base("name=EF6CodeFirstRecipesContext")
        {
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Product>()
            .Map(m =>
            {
                m.Properties(p => new { p.SKU, p.Description, p.Price });
                m.ToTable("Product", "Chapter2");
            })
            .Map(m =>
            {
                m.Properties(p => new { p.SKU, p.ImageURL });
                m.ToTable("ProductWebInfo", "Chapter2");
            });
        }
    }

3.生成数据

public static void InsertProduct()
        {
            //Database.SetInitializer<ProductContext>(null);

            using (var context = new ProductContext())
            {
                var product = new Product
                {
                    SKU = 147,
                    Description = "Expandable Hydration Pack",
                    Price = 19.97M,
                    ImageURL = "/pack147.jpg"
                };
                context.Products.Add(product);
                product = new Product
                {
                    SKU = 178,
                    Description = "Rugged Ranger Duffel Bag",
                    Price = 39.97M,
                    ImageURL = "/pack178.jpg"
                };
                context.Products.Add(product);
                product = new Product
                {
                    SKU = 186,
                    Description = "Range Field Pack",
                    Price = 98.97M,
                    ImageURL = "/noimage.jp"
                };
                context.Products.Add(product);
                product = new Product
                {
                    SKU = 202,
                    Description = "Small Deployment Back Pack",
                    Price = 29.97M,
                    ImageURL = "/pack202.jpg"
                };
                context.Products.Add(product);
                context.SaveChanges();
            }
            using (var context = new ProductContext())
            {
                foreach (var p in context.Products)
                {
                    Console.WriteLine("{0} {1} {2} {3}", p.SKU, p.Description,
                    p.Price.ToString("C"), p.ImageURL);
                }
            }
        }

做到这里,认为就能成功运行插入新的产品,简直太天真了。

问题一,无法连接数据库,对象模型不存在:

An unhandled exception of type ‘System.InvalidOperationException‘ occurred in EntityFramework.dll

Additional information: The entity type Product is not part of the model for the current context.

解决办法:

木有仔细研究,试验了一下,发现是App.config中DB连接串的问题

原来的链接串:

<add name="EF6RecipesContext" connectionString="metadata=res://*/TestModel.csdl|res://*/TestModel.ssdl|res://*/TestModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DST60519\SQLEXPRESS;initial catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

修改后的连接串:

<add name="EF6CodeFirstRecipesContext" providerName="System.Data.SqlClient" connectionString="Data Source=DST60519\SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"/>

EF生成链接串是  providerName="System.Data.EntityClient"

而CodeFirst生成串是  providerName="System.Data.SqlClient"

修改后就可以了?太天真!

问题二,DbContext生成异常:

经过修改后运行,发现还是会报错

The model backing the ‘ProductContext‘ context has changed since the database was created.

Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

查一下网上的资料:

For those who are seeing this exception:

"The model backing the ‘Production‘ context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance."

Here is what is going on and what to do about it:

When a model is first created, we run a DatabaseInitializer to do things like create the database if it‘s not there or add seed data. The default DatabaseInitializer tries to compare the database schema needed to use the model with a hash of the schema stored in an EdmMetadata table that is created with a database (when Code First is the one creating the database). Existing databases won’t have the EdmMetadata table and so won’t have the hash…and the implementation today will throw if that table is missing. We‘ll work on changing this behavior before we ship the fial version since it is the default. Until then, existing databases do not generally need any database initializer so it can be turned off for your context type by calling:

Database.SetInitializer<YourDbContext>(null);
(http://stackoverflow.com/questions/3600175/the-model-backing-the-database-context-has-changed-since-the-database-was-crea)

所以说,在使用数据的时候,就要先戳一下连接串,告诉它我们要来了,在使用前加上:Database.SetInitializer<ProductContext>(null);

然后就可以走通了,yeah!

但是报了个错:

Violation of PRIMARY KEY constraint ‘PK_Chapter2.Product‘.
Cannot insert duplicate key in object ‘Chapter2.Product‘. The duplicate key value is (147).
The statement has been terminated.

原因待查ing

EF好难搞!!!

The model backing the 'ProductContext' context has changed since the database was created. EF6

时间: 2024-08-04 21:16:16

The model backing the 'ProductContext' context has changed since the database was created. EF6的相关文章

Model backing a DB Context has changed; Consider Code First Migrations

Model增加一个字段,数据库对应的也手动添加了字段但是运行时报错 The model backing the 'TopLogDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database  参考原文:Model backing a DB Context has changed; Consider Code Firs

Entity Framework : The model backing the &#39;&#39; context has changed since the database was created

1.采用code first 做项目时,数据库已经生成,后期修改数据库表结构.再次运行时出现一下问题: Entity Framework : The model backing the 'ProductModel' context has changed since the database was create 解决方法: 1.打开当前项目中的:程序包管理器控制台 2.输入:enable-migrations -ProjectName 'ProductModel' -Force 解释:'Pro

EF Code First(The model backing the &#39;***&#39; context has changed since the database was created.解决方法)(CSDN手动迁移)

错误消息: The model backing the '***' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269). 错误原因: (1)数据模型发生改变,而没有更新到数据库导致此问题. 事实上我遇到的情况不是原因(1),而是(2

The model backing the &#39;XXX&#39; context has changed 错误

https://blog.csdn.net/hit_why/article/details/72778785 https://blog.csdn.net/hit_why/article/details/72778785 The model backing the 'XXX' context has changed 错误 原创 2017年05月27日 10:18:47 271 使用Entity FrameWork的Code First时,当改变模型的结构时,运行程序会出现The model bac

The entity type &lt;type&gt; is not part of the model for the current context

这是在网站里遇到的一个错误,自动生成的不能手动添加, reference: http://stackoverflow.com/questions/19695545/the-entity-type-xxx-is-not-part-of-the-model-for-the-current-context When I created a strong view using the Quickfix context it blew up, because it was trying to associ

《转》Model First

我们将开始于BAGA业务域的一个小片断:包括我们旅行的目的地和我们的奇客们在这次旅行的住所. Code First的美妙在于域类的定义代码与EF数据模型所依赖的代码是一样的.我们只需要开始于代码就可以了,例2-1,分别展示了Destination类和Loadging类.在开始的案例中,我们要保持类的简洁:这些类包含了一些自动属性,并没有什么逻辑. Example 2-1. The domain model publicclassDestination { publicint Destinatio

[EF] 如何在 Entity Framework 中以手动方式设定 Code First 的 Migration 作业

Entity Framework (简称 EF) 发展到现在, 版本已经进入 6.1.0, 距离我写的「在 VS2013 以 Code First 方式建立 EF 资料库」这篇文章已有半年的时间.如果你和我一样从那时候开始使用 EF Code First, 那么你对 EF 应该已经有了基本的了解.依我个人的使用经验, EF 虽然好用, 但是如果一直使用 AutomaticMigrations 的方式维护你的资料库, 也许会遇到一些麻烦.因为在正常作业环境下, 资料库的格式不可能永远不变; 当我们

MVC5+EF6--6 创建更复杂的数据模型

近期学习MVC5+EF6,找到了Microsoft的原文,一个非常棒的系列,Getting Started with Entity Framework 6 Code First using MVC 5,网址:http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-appli

【译著】Code First :使用Entity. Framework编程(6)

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 Chapter6 Controlling Database Location,Creation Process, and Seed Data 第6章 控制数据库位置,创建过程和种子数据 In previous chapters you have