c# - Why EF not updating FK column when entity state is not Added? -


i have such entity:

 public class entity1     {         public short id { get; set; }         public int entity2id { get; set; }         public virtual entity2 entity2 { get; set; }     } 

and have such 1 many relationship:

  this.hasrequired(m => m.entity2)             .withmany()             .hasforeignkey(m => m.entity2id)             .willcascadeondelete(false); 

and here thinkg cannot understand:

for example, evertyhting works fine if have changed entity state added firstly:

context.entry(entity1).state = system.data.entitystate.added; entity1.entity2.id = 541;   // since line `entity1.entity2id` value 0.  context.entry(entity1.entity2).state = system.data.entitystate.unchanged;  // fine, because `entity1.entity2id` value 541 also.   context.entry(entity1).state = system.data.entitystate.unchanged; 

but, don't want change state added, when removing first line, exception occured:

a referential integrity constraint violation occurred: property values define referential constraints not consistent between principal , dependent objects in relationship.

beacuse, entit1.entity2id != entity1.entity2.id.

and, don't want manually change value.

how, can make work without changing state added?

update:

i have investigated problem more. so question:

this called property fixup, , used done automatically generated proxies. however, dbcontext no longer case. according connect issue, design.

hello, dbcontext template doesn't generate classes used change tracking proxies - lazy loading proxies (which don't fix-up). made decision because change tracking proxies complex , have lot of nuances can confusing developers. if want fix-up occur before savechanges can call mycontext.changetracker.detectchanges. ~ef team

an alternative call dbcontext.entry(entity), sync entity. described in article: relationships , navigation properties under "synchronizing changes between fks , navigation properties"


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -