首页 > 解决方案 > EF Core 5:模型之间的依赖关系

问题描述

我有以下 2 个模型,位置和标称。Nominals 有一个 Location 的外键,Location 可以有许多不同的默认 Nominals 用于不同的目的。

public class Nominal
{
    [Key]
    public Guid Id { get; set; }
    public string NominalCode { get; set; }
    public string Description { get; set; }
    public char Analysis { get; set; }

    // link to location

    public Guid LocationId { get; set; }
    public Location Location { get; set; }       

}

位置模型如下所示;

public class Location : AutoTracking
{
    [Key]
    public Guid Id { get; set; }
    public int LocationCode { get; set; }
    public string LocationName { get; set; }
    [ForeignKey("Nominal")]
    public Guid? DefaultNominal1Id { get; set; }
    public Nominal DefaultNominal1 { get; set; }
    [ForeignKey("Nominal")]
    public Guid? DefaultNominal2Id { get; set; }
    public Nominal DefaultNominal2 { get; set; }
}

由于 Nominal 已经具有 Location 链接,因此从 Location 返回 Nominal 的链接会生成错误。错误中建议的解决方案是将 [NotMapped] 属性添加到导航属性中,我已经这样做了。

添加未映射是否有任何副作用,我假设我仍然可以使用 EF 核心延迟加载加载导航属性?

标签: .netentity-framework-coreef-core-5.0

解决方案


尝试更改您的课程:

public partial class Nominal
{
    [Key]
    public Guid Id { get; set; }
    public string NominalCode { get; set; }
    public string Description { get; set; }
    public char Analysis { get; set; }

    // link to location

    public Guid LocationId { get; set; }
   [ForeignKey(nameof(LocationId))]
    [InverseProperty("Nominals")]
    public virtual Location Location{ get; set; }

public partial class Location : AutoTracking
{
    [Key]
    public Guid Id { get; set; }
    public int LocationCode { get; set; }
    public string LocationName { get; set; }
    [InverseProperty(nameof(Nominal.Location))]
     public virtual ICollection<Nominal> Nominals{ get; set; }
}

如果由于某些原因您需要更多属性,您可以通过以下方式添加它们:

public partial class Location : AutoTracking
{ 
 [NotMapped]
   public Guid? DefaultNominal1Id { get; set; }
 [NotMapped]
    public Nominal DefaultNominal1 { get; set; }
    [NotMapped]
    public Guid? DefaultNominal2Id { get; set; }
 [NotMapped]
    public Nominal DefaultNominal2 { get; set; 
}

但是您只能手动为它们分配值。


推荐阅读