gpt4 book ai didi

entity-framework - 自引用 1 对多关系

转载 作者:行者123 更新时间:2023-12-03 23:39:13 25 4
gpt4 key购买 nike

我有以下实体:

 public class TravelCoverageType
{
public int Code { get; set; }

public virtual TravelCoverageType PreventedBy { get; set; }

public ICollection<TravelCoverageType> PreventCoverages { get; set;}
...
}

每个TravelCoverageType可以阻止0个或多个TravelCoverageType

我正在使用流畅的 API,但无法弄清楚如何描述这种关系。

我试过:

public TravelCoverageTypeConfiguration()
{
ToTable(ConfigConstants.TypeTablePrifix + typeof(TravelCoverageType).Name + "s");
HasKey(ct => ct.Code);

HasMany(tc => tc.PreventCoverages)
.WithOptional(tc=>tc.PreventedBy)
.HasForeignKey(tc => tc.Code);
}

但是我得到以下错误:

System.Data.Entity.Edm.EdmAssociationType: : Multiplicity conflicts with the referential constraint in Role 'TravelCoverageType_PreventCoverages_Source' in relationship 'TravelCoverageType_PreventCoverages'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

System.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'TravelCoverageType_PreventCoverages_Target' in relationship 'TravelCoverageType_PreventCoverages'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.

(我添加了 PreventedBy 来简化关系的定义,我真的不需要它)

这是怎么做到的?

最佳答案

是否必须使用 Fluent API 来完成?我不太了解它,但您可以改为使用数据注释执行以下操作:

public class TravelCoverageType
{
[Key]
public int Code { get; set; }

[ForeignKey("PreventedBy")]
public int? PreventedByID { get; set; }

public virtual TravelCoverageType PreventedBy { get; set; }

public ICollection<TravelCoverageType> PreventCoverages { get; set;}
}

编辑:仔细观察您的问题,我注意到您正在尝试将 Code 属性用作 FK:

.HasForeignKey(tc => tc.Code);

EF 根本不喜欢这样,因为您看到的异常(exception)情况(它告诉您,如果您也想将主键设为 FK,则只能按 1:1 比例执行,而不是1:很多)。尝试向该类添加一个新属性(就像我在上面的数据注释示例中所做的那样),然后将配置更改为:

HasMany(tc => tc.PreventCoverages)
.WithOptional(tc => tc.PreventedBy)
.HasForeignKey(tc => tc.PreventedByID);

关于entity-framework - 自引用 1 对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28340202/

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