Entity framework update foreign key to null without query and without id of the related entity

一笑奈何 提交于 2019-12-12 03:25:19

问题


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



来源:https://stackoverflow.com/questions/28106714/entity-framework-update-foreign-key-to-null-without-query-and-without-id-of-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!