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

Source: Internet
Author: User

Learn "Entity Framework 6 Recipes 2nd Edition", 2-6. Several problems encountered in splitting an Entity among multiple tables

Table structure:

Operation

1. Constructing Data Objects

 Public classProduct {[Key] [databasegenerated (databasegeneratedoption.none)] Public intSKU {Get;Set; }  Public stringDescription {Get;Set; }  Public decimalPrice {Get;Set; }  Public stringImageURL {Get;Set; } }

2. Construction DbContext

 Public classProductcontext:dbcontext { PublicDbset<product> Products {Get;Set; }  PublicProductcontext ():Base("Name=ef6codefirstrecipescontext")        {        }        protected Override voidonmodelcreating (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. Generating data

 Public Static voidinsertproduct () {//database.setinitializer<productcontext> (null);            using(varContext =NewProductcontext ()) {                varProduct =NewProduct {SKU=147, Description="Expandable Hydration Pack", Price=19.97M, ImageURL="/pack147.jpg"                }; Context.                Products.add (product); Product=NewProduct {SKU=178, Description="Rugged Ranger Duffel Bag", Price=39.97M, ImageURL="/pack178.jpg"                }; Context.                Products.add (product); Product=NewProduct {SKU=186, Description="Range Field Pack", Price=98.97M, ImageURL="/noimage.jp"                }; Context.                Products.add (product); Product=NewProduct {SKU=202, Description="Small Deployment back Pack", Price=29.97M, ImageURL="/pack202.jpg"                }; Context.                Products.add (product); Context.            SaveChanges (); }            using(varContext =NewProductcontext ()) {                foreach(varPinchcontext. Products) {Console.WriteLine ("{0} {1} {2} {3}", P.sku, P.description, p.price.tostring ("C"), P.imageurl); }            }        }

It's naïve to think that it will be possible to successfully run a new product.

Problem one, the database cannot be connected and the object model does not exist:

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.

Workaround:

The wood has been carefully studied and tested and found to be a problem with the DB connection string in app. Config

The original link string:

<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" />

Modified connection string:

<name= "Ef6codefirstrecipescontext"  providerName= " System.Data.SqlClient "  connectionString=" Data source=dst60519\sqlexpress;initial catalog=testdb ; Integrated Security=true; Multipleactiveresultsets=true; Application Name=entityframework "/>

EF generated link string is Providername= "System.Data.EntityClient"

and Codefirst generated string is Providername= "System.Data.SqlClient"

You can change it? Too naïve!

Issue two, DbContext generates an exception:

After the change to run, found or will be error

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

Check the information on the Internet:

For those who is seeing this exception:

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

Here's what's going on and what's about it:

When a model was 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 sto The red in an Edmmetadata table, created with a database (when Code first is the one creating the database). Existing databases won ' t has the Edmmetadata table and so won ' t has the hash...and the implementation today would throw if That table is missing. We'll work on changing this behavior before we ship the fial version since it's the default. Until then, existing databases don't generally need any database initializer so it can turned off for your context Typ E by calling:

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

So, in the use of data, it is necessary to poke a connection string, tell it we are coming, before using:database.setinitializer<productcontext> (NULL);

And then you can walk through it, yeah!.

But there was a mistake:

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.

Reason unknown origin ing

EF is so hard to do!!!

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.