在 EF Code First 中启用级联删除而不暴露外键

发布于 2024-10-24 11:49:39 字数 682 浏览 5 评论 0原文

在不公开外键的情况下执行一对多关系的删除时,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆蝶 2024-10-31 11:49:39

是的!删除JobId并添加以下内容:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Job>().HasMany(j => j.Projects).WithRequired();
    }

在数据库中,这将在PK/FK关系中添加级联删除。

(我假设您的 ModelBase 有一个整数 Id =)

Yup! Remove JobId and add the following:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Job>().HasMany(j => j.Projects).WithRequired();
    }

In the database, this will add a cascading delete in the PK/FK relationship.

(I'm assuming that your ModelBase has an integer Id =)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文