简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM