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:

  1. entity framework determines needs updated during savechanges tracking changes property values.
  2. you have lazy loading enabled (both in general , work property), means if person has associated work, 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

  1. if want remove association without loading related entity, you'll need add foreign key property person entity, 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(); 
  2. octavioccl's answer quoted option:

    context.entry(person).reference(p => p.work).currentvalue = null;


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -