Entity framework update foreign key to null withou

2019-09-03 17:50发布

问题:

Using EF 6.1, I want to set a foreign key to null (break the relation between two entities), without querying for either object first. Preferably, I also don't want to supply the id of the related entity (since that requires adding it to my HTML).

My current code doesn't do unnecessary queries, but requires the id of the related entity:

public void RemoveCurrentTeacherOfGroup(int groupId, int teacherId)
{
    var group = new Group { Id = groupId };
    var teacher = new Teacher { Id = teacherId };
    group.Teacher = teacher;
    _dataContext.Groups.Attach(group);
    _dataContext.Teachers.Attach(teacher);

    group.Teacher = null;

    _dataContext.SaveChanges();
}

However, I shouldn't need the teacherId, the groupId is enough information.

Further information: 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; }
}

Is there a way to set the foreign key to null without the teacherId?

Also, many kudos for an answer that makes the code less verbose, I feel these are far too many lines for something as simple as setting a foreign key to null.

回答1:

Life is generally much easier if you add the foreign key to the class:

public class Group
{
    public int Id { get; set; }
    public int? TeacherId { get; set; }
    public virtual Teacher Teacher { get; set; }
}

And then your method is:

public void RemoveCurrentTeacherOfGroup(int groupId)
{
   var group = dataContext.Groups.Find(groupId);
   if(group == null)
     return;
   group.TeacherId = null;
   _dataContext.SaveChanges();
}

References:

Why does Entity Framework Reinsert Existing Objects into My Database?

Making Do with Absent Foreign Keys