在 EF Code First 中启用级联删除而不暴露外键
在不公开外键的情况下执行一对多关系的删除时,EF 会删除父记录并尝试将子记录上的外键设为 null。这当然会导致错误,因为外键不可为空。将外键添加到子类会覆盖此行为,但我不想公开它。
例如,给定以下两个类,我不希望将 JobId 作为 Project 类的属性。
public class Job : ModelBase
{
[Required]
[StringLength(100)]
public string Company { get; set; }
[Required]
[StringLength(100)]
public string JobTitle { get; set; }
public ICollection<Project> Projects { get; set; }
}
public class Project : ModelBase
{
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
public string Summary { get; set; }
public int JobId { get; set; }
}
有没有办法在 EF Code First 中启用级联删除而不暴露关系多方的外键?
When performing a delete of a one-many relationship without exposing the foreign key, EF deletes the parent record and tries to null the foreign key on the child records. This of course causes an error because the foreign key is not nullable. Adding the foreign key to the child class overrides this behavior, but I'd rather not expose it.
For example given the following two classes, I'd prefer not to have JobId as a property of the Project class.
public class Job : ModelBase
{
[Required]
[StringLength(100)]
public string Company { get; set; }
[Required]
[StringLength(100)]
public string JobTitle { get; set; }
public ICollection<Project> Projects { get; set; }
}
public class Project : ModelBase
{
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
public string Summary { get; set; }
public int JobId { get; set; }
}
Is there a way to enable cascading deletes in EF Code First without exposing the foreign key on the many side of the relationship?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的!删除JobId并添加以下内容:
在数据库中,这将在PK/FK关系中添加级联删除。
(我假设您的 ModelBase 有一个整数 Id =)
Yup! Remove JobId and add the following:
In the database, this will add a cascading delete in the PK/FK relationship.
(I'm assuming that your ModelBase has an integer Id =)