在 .NET 6 中创建数据库时出错

问题描述 投票:0回答:1

在编辑

ContractTypeOne
ContractTypeTwo
模型时,我收到此错误:

在表“ContractTypeTwos”上引入外键约束“FK_ContractTypeTwos_ContractTypeOnes_ContractTypeOneId”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他外键约束。
无法创建约束或索引。查看之前的错误。

我希望在删除

ContractTypeTwo
后删除
ContractTypeOne
。但删除
Contract
后我不想删除
ContractTypeOne

namespace ContractAppAPI.Models
{
    public class Contract
    {
        public int Id { get; set; }
        public int ContractNumber { get; set; }
        public string Name { get; set; }
        public DateTime DateOfConclusion { get; set; }
        public string Description { get; set; }
        public decimal Value { get; set; }
        public string Contractor { get; set; }
        public string Signatory { get; set; }
        public Boolean HasPdf { get; set; }
        public ContractTypeOne ContractTypeOne { get; set; }
        public ContractTypeTwo ContractTypeTwo { get; set; }
        public ICollection<ContractPdf> ContractPdfs { get; set; }
        public ICollection<AnnexToTheContract> AnnexToTheContracts { get; set; }
    }

    public class ContractTypeOne
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<Contract> Contracts { get; set; }
        public ICollection<ContractTypeTwo> ContractTypeTwos { get; set; }
    }

    public class ContractTypeTwo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int ContractTypeOneId { get; set; }
        public ContractTypeOne ContractTypeOne { get; set; }
        public ICollection<Contract> Contracts { get; set; }
    }
}
modelBuilder.Entity<ContractTypeOne>()
    .HasMany(cto => cto.ContractTypeTwos)
    .WithOne(ctt => ctt.ContractTypeOne)
    .HasForeignKey(ctt => ctt.ContractTypeOneId)
    .OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<ContractTypeTwo>()
    .HasOne(ctt => ctt.ContractTypeOne)
    .WithMany(cto => cto.ContractTypeTwos)
    .HasForeignKey(ctt => ctt.ContractTypeOneId)
    .OnDelete(DeleteBehavior.NoAction);
c# sql-server entity-framework foreign-keys
1个回答
1
投票

这可确保

Contract
实体持续存在,即使其相关的
ContractTypeOne
ContractTypeTwo
已被删除。

modelBuilder.Entity<ContractTypeOne>()
    .HasMany(cto => cto.ContractTypeTwos)
    .WithOne(ctt => ctt.ContractTypeOne)
    .HasForeignKey(ctt => ctt.ContractTypeOneId)
    .OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<Contract>()
    .HasOne(c => c.ContractTypeOne)
    .WithMany(cto => cto.Contracts)
    .HasForeignKey(c => c.ContractTypeOneId)
    .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<Contract>()
    .HasOne(c => c.ContractTypeTwo)
    .WithMany(ctt => ctt.Contracts)
    .HasForeignKey(c => c.ContractTypeTwoId)
    .OnDelete(DeleteBehavior.Restrict);
© www.soinside.com 2019 - 2024. All rights reserved.