c# - Entity Framework 4: Table per Type inheritance problem on insert -


i have simple model "baseentity" , derived "fund" entity. when try insert new fund:

hybridmodelcontainer container = new hybridmodelcontainer();  //create new fund fund fund = new fund(); fund.id = guid.newguid(); fund.datecreated = datetime.now; fund.name = "fund 1"; fund.number = 1; container.baseentities.addobject(fund);  container.savechanges(); 

i following error:

"cannot insert value null column 'id', table 'hybriddata.dbo.baseentities'; column not allow nulls. insert fails.
statement has been terminated."

it seems id assigned fund entity not inserted baseentity table. why not?

i did "model first". if design database first, , create model it, works fine....but need model first!

enter image description here

also...why isn't there objectset "funds" in datacontext (i.e., container.funds)? in advance help!

i can answer second part of question: "also...why isn't there objectset "funds" in datacontext (i.e., container.funds)?"

it's normal objectcontext has objectset of base class in class hierarchy. there isn't need objectset of derived classes. adding , deleting derived objects to/from objectcontext can use addobject , deleteobject methods of objectset<baseentity> / baseentities did in example.

for querying derived objects can leverage oftype method of objectset. returns objectquery of derived type can build further queries upon:

objectquery<fund> query = container.baseentities.oftype<fund>(); 

(the first part of question sounds mapping error between storage , conceptual model. might have better cif show relevant parts of edmx file.)

edit: possible solution first part of question:

i've created example model-first in vs2010 , reproduce issue. problem seems related fact primary key in model isn't int32 guid. when add new entity model designer proposes int32 primary key storegeneratedpattern set identity.

if change type of key in model designer int32 guid leave storegeneratedpattern unchanged being identity, ddl creates database in sql server id set type uniqueidentifier identity specification column "no".

so, when ef sends insert command db "thinks" model definition primary autogenerated in db , doesn't send guid db have assigned in code. db doesn't create key, resulting in null value key. hence error get.

solution: set in model designer id property of baseentity storegeneratedpattern none. me worked then. of course, responsible assign guid id before add new object objectset, seems want anyway.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -