简体   繁体   English

实体框架将外键更新为null,无需查询且没有相关实体的id

[英]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. 使用EF 6.1,我想将外键设置为null(破坏两个实体之间的关系),而不先查询任何一个对象。 Preferably, I also don't want to supply the id of the related entity (since that requires adding it to my HTML). 最好,我也不想提供相关实体的ID(因为这需要将其添加到我的HTML中)。

My current code doesn't do unnecessary queries, but requires the id of the related entity: 我当前的代码不会执行不必​​要的查询,但是需要相关实体的ID:

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. 但是,我不需要教师ID,groupId是足够的信息。

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? 有没有办法在没有TeacherId的情况下将外键设置为null?

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. 另外,对于使代码不那么冗长的答案的许多赞誉,我觉得对于将外键设置为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 使用缺少的外键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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