实体框架将外键更新为空,无查询,无相关实体的ID [英] Entity framework update foreign key to null without query and without id of the related entity
问题描述
使用EF 6.1,我想将外键设置为null(打破两个实体之间的关系),而不首先查询任一对象。最好,我也不想提供相关实体的ID(因为这需要将其添加到我的HTML中)。
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).
我当前的代码不做不必要查询,但需要相关实体的ID:
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();
}
但是,我不应该需要teacherId,groupId是足够的信息。
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; }
}
有没有办法将外键设置为null,而没有teacherId?
Is there a way to set the foreign key to null without the teacherId?
此外,许多令人遗憾的答案使得代码不那么冗长,我觉得这些对于像外键设置为空的东西来说太多了。 / p>
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; }
}
然后你的方法是:
public void RemoveCurrentTeacherOfGroup(int groupId)
{
var group = dataContext.Groups.Find(groupId);
if(group == null)
return;
group.TeacherId = null;
_dataContext.SaveChanges();
}
参考文献:
这篇关于实体框架将外键更新为空,无查询,无相关实体的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!