Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relationship not set to null

I have a very simple EF operation that fails: break the relationship between two entities as shown in the code below:

public async Task RemoveCurrentTeacherOfGroup(int groupId)
{
    var group = await _dataContext.Groups.SingleAsync(g => g.Id == groupId);
    group.Teacher = null;
    await _dataContext.SaveChangesAsync();
}

The database was generated code-first. The entities are defined like this:

public class Teacher
{
    public int Id { get; set; }
    ..
    public virtual List<Group> Groups { get; set; }
}
public class Group
{
    public int Id { get; set; }
    ..
    public virtual Teacher Teacher { get; set; }
}

However, breaking the relationship doesn't work, Teacher keeps pointing to the same entity. When stepping with the debugger, I see that the Teacher property doesn't become null after .Teacher = null. I tried it with the synchronous alternative, which had the same effect:

public void RemoveCurrentTeacherOfGroup(int groupId)
{
    var group = _dataContext.Groups.Single(g => g.Id == groupId);
    group.Teacher = null;
    _dataContext.SaveChanges();
}
like image 378
mnwsmit Avatar asked Jan 22 '15 16:01

mnwsmit


1 Answers

If Teacher is not loaded you can't break the relationship. Either include it (eager-load) on the query:

_dataContext.Groups.Include(g => g.Teacher).Single(g => g.Id == groupId);

Or if lazy loading is enabled, access the property for reading before setting it to null:

var teacher = group.Teacher;
group.Teacher = null;

You see that "Teacher is not null after setting it to null" because the debugger is accessing the property for reading (lazy-loading it) after you have set it to null.

The value was already null before you hit the group.Teacher = null line since you hadn't previously loaded it (you can't however debug this, since accessing the property for reading would cause EF to actually load it if lazy loading is enabled). If you see the property value with the debugger before setting it to null, it'll work as expected and break the relationship, since Teacher would be loaded

like image 51
Jcl Avatar answered Oct 22 '22 17:10

Jcl