How to properly Delete fields of an Entity? -
i having trouble when trying delete field of entity using entity framework (version 6.1.3).
let's have 2 entities: person , work. can change work of person without issue, when try express person unemployed not work properly:
 person.work = null;  db.savechanges(); after running code person still have previous work, if use debugger , check work property of person before running  person.work = null;, behave expected. 
can please explain why reading value first makes code work , how correctly delete field?
 var work = person.work; \\ line here works expected  person.work = null;  db.savechanges(); 
two things contributing issue:
- entity framework determines needs updated during savechangestracking changes property values.
- you have lazy loading enabled (both in general , workproperty), means ifpersonhas associatedwork, associated entity doesn't loaded until first time access property.
putting together, when set person.work = null without accessing person.work (which trigger load), context thinks nothing has changed. if load property first, setting property null tells ef remove association. edit: according the page octavioccl linked, true .net 4.0., .net 4.5+ (and ef 5+), loading first unneeded.
possible solutions
- if want remove association without loading related entity, you'll need add foreign key property - personentity, can set null instead of setting navigation property null. example:- public class person { // other properties... public int? workid { get; set; } public virtual work { get; set; } }- person.workid = null; db.savechanges();
- octavioccl's answer quoted option: - context.entry(person).reference(p => p.work).currentvalue = null;
Comments
Post a Comment