GTHvidsten GTHvidsten - 3 months ago 8
C# Question

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

I have a Code First model in Entity Framework version 6.1.1 that basically looks like this:

public class TinMan {
public int Id { get; set; }
public virtual Heart Heart { get; set; }
}

public class Heart {
public int Id { get; set; }
}


This is represented in an actual database like this, where the
Heart_Id
column is generated automatically by EF which also creates the foreign key relationship between the two tables:

TinMen: Hearts:

Id Heart_Id Id
1 1 1
2 3 2
3 NULL 3


Creating a relation where none exist, or changing an existing relation works just 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 I try to remove a relation:

using (MyDbContext dbContext = new MyDbContext()) {
TinMan jebediah = dbContext.TinMen.FirstOrDefault(man => man.Id == 2);
if (jebediah != null) jebediah.Heart = null;
dbContext.SaveChanges();
}


After this has been executed TinMan with ID==2 still has a Heart in the database, i.e. it was not set to
NULL
in the database.

Why?

Answer

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 is an alternate way of doing it, based on my 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 any case, this is a scenario where having an explicit foreign key property (ex. public int? HeartId { get; set; } can be advantageous. With a foreign key property, you can remove a relationship without pre-loading the related entity. For example:

using (MyDbContext dbContext = new MyDbContext())
{
    TinMan jebediah = dbContext.TinMen.FirstOrDefault(man => man.Id == 2);
    jebediah.HeartId = null;
    dbContext.SaveChanges();
}