gpt4 book ai didi

c# - 是否可以在没有外键的情况下设置导航属性?

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:44 26 4
gpt4 key购买 nike

是否可以有两个(或更多)相同类型的导航属性?

我的模型看起来像这样......

public class Agreement
{
public int Id { get; set; }
public Guid? BuyerId { get; set; }
public Guid? SellerId { get; set; }

public AgreementInfo ByerAgreementInfo { get; set; }
public AgreementInfo SellerAgreementInfo { get; set; }
}

public class AgreementInfo
{
// PK is AgreementId and OwnerActorId combined.
public int AgreementId { get; set; }
public Guid OwnerActorId { get; set; }
public string Name { get; set; }
}

...我正在尝试通过匹配 AgreementId 和 ByerId/SellerId 来包含导航属性...

modelBuilder.Entity<Agreement>().HasOne(x => x.ByerAgreementInfo).WithOne().HasForeignKey<Agreement>(x => new {x.Id, x.ProviderId});
modelBuilder.Entity<Agreement>().HasOne(x => x.SellerAgreementInfo).WithOne().HasForeignKey<Agreement>(x => new { x.Id, x.RequesterId });

... but this results in a circural dependecy.

有没有办法不使用外键就包含这些属性?或者是否有另一种解决方案(除了向信息表添加一个 id 列)允许我将信息表行用作协议(protocol)类中的导航属性?

最佳答案

... but this results in a circural dependecy

是的!它会。要克服这个问题,您必须在 Fluent API 配置中指定 .OnDelete(DeleteBehavior.Restrict);,如下所示,但首先您必须编写您的协议(protocol) 模型类也如下:

public class Agreement
{
public int Id { get; set; }
public Guid? BuyerId { get; set; }
public Guid? SellerId { get; set; }

public int AgreementIdForBuyer { get; set; }
public Guid OwnerActorIdForBuyer { get; set; }

public int AgreementIdForSeller { get; set; }
public Guid OwnerActorIdForSeller { get; set; }

public AgreementInfo ByerAgreementInfo { get; set; }
public AgreementInfo SellerAgreementInfo { get; set; }
}

现在在 Fluent API 配置中:

modelBuilder.Entity<Agreement>()
.HasOne(x => x.ByerAgreementInfo)
.WithOne()
.HasForeignKey<Agreement>(p => new {p.AgreementIdForBuyer, p.AgreementIdForBuyer})
.OnDelete(DeleteBehavior.Restrict); // <-- Here it is

modelBuilder.Entity<Agreement>()
.HasOne(x => x.SellerAgreementInfo)
.WithOne()
.HasForeignKey<Agreement>(p => new {p.AgreementIdForSeller, p.OwnerActorIdForSeller})
.OnDelete(DeleteBehavior.Restrict); // <-- Here it is

关于c# - 是否可以在没有外键的情况下设置导航属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56998202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com