c# - EF Relationship (1 to 0..1) won't be removed -


i have code first model in entity framework version 6.1.1 looks this:

public class tinman {     public int id { get; set; }     public virtual heart heart { get; set; } }  public class heart {     public int id { get; set; } } 

this represented in actual database this, heart_id column generated automatically ef creates foreign key relationship between 2 tables:

tinmen:                 hearts:  id    heart_id          id 1     1                 1 2     3                 2 3     null              3 

creating relation none exist, or changing existing relation works fine:

using (mydbcontext dbcontext = new mydbcontext()) {     tinman bill = dbcontext.tinmen.firstordefault(man => man.id == 1);     if (bill != null) bill.heart = 2;     tinman bob = dbcontext.tinmen.firstordefault(man => man.id == 3);     if (bob != null) bob.heart = 1;     dbcontext.savechanges(); } 

now try remove relation:

using (mydbcontext dbcontext = new mydbcontext()) {     tinman jebediah = dbcontext.tinmen.firstordefault(man => man.id == 2);     if (jebediah != null) jebediah.heart = null;     dbcontext.savechanges(); } 

after has been executed tinman id==2 still has heart in database, i.e. not set null in database.

why?

try this:

using (mydbcontext dbcontext = new mydbcontext()) {     tinman jebediah = dbcontext.tinmen.firstordefault(man => man.id == 2);     context.entry(jebediah).reference(t => t.heart).currentvalue = null;     dbcontext.savechanges(); } 

this alternate way of doing it, based on comment:

using (mydbcontext dbcontext = new mydbcontext()) {     tinman jebediah = dbcontext.tinmen.firstordefault(man => man.id == 2);     context.entry(jebediah).reference(t => t.heart).load();     jebediah.heart = null;     dbcontext.savechanges(); } 

in case, scenario having explicit foreign key property (ex. public int? heartid { get; set; } can advantageous. foreign key property, can remove relationship without pre-loading related entity. example:

using (mydbcontext dbcontext = new mydbcontext()) {     tinman jebediah = dbcontext.tinmen.firstordefault(man => man.id == 2);     jebediah.heartid = null;     dbcontext.savechanges(); } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -