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

1

0

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.

Nailbiting answered 23/1, 2015 at 9:28 Comment(0)
I
0

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

Into answered 23/1, 2015 at 10:27 Comment(3)
Sorry, can't mark this as the answer because Find(groupId) will do an extra query (unless the dataContext is cached which will complicate the architecture and create many possible issues)Nailbiting
You want to remove the Teacher from a Group when neither is attached to the DbContext? And you want to use Entity Framework?Into
I want to do that yes, preferably with EF. However "It's not possible with EF" might be the answer, I don't know if it isNailbiting

© 2022 - 2024 — McMap. All rights reserved.