在 EF Code First 中使用动态导航 属性 或 BaseEntity

Using Dynamic Navigation Property or BaseEntity in EF Code First

这道题可能很简单,但是逻辑很重要,我很困惑。在 Asp.Net Core 2.1 with Entity Framework Core Code First 中,我想学习如何建模,所以我简化了问题。两个不同实体(中心和文章)中的一个相同导航 属性(照片)。中心可以有很多照片,文章可以有一张照片。一张照片可以有一个 post 或一个中心,因此可以有一个 MyEntityBase。示例:

public class Photo
{
    public int Id { get; set; }
    public string Url { get; set; }

    //The question/relation problem is here???
    //public int CenterId { get; set; }
    //public virtual Center Center { get; set; }

    //public int ArticleId { get; set; }
    //public virtual Article Article{ get; set; }

    //public int MyEntityBaseId { get; set; }
    //public virtual MyEntityBase ArticleOrPost{ get; set; }
}

public class Article: MyEntityBase
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; } 

    //Common Photo property
    //One article has one photo
    public virtual Photo ArticlePhoto { get; set; }

}
public class Center: MyEntityBase
{
    [Key]
    public int Id { get; set; }

    public string Name{ get; set; } 

    //Common Photo property
    //One center has many photo
    public virtual List<Photo> CenterPhotos { get; set; }

}  

乍一看,如果您使用的是 Entity Framework 核心...请不要使用 virtual

因此您的 Article 对象应该如下所示

public class Article: MyEntityBase
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; } 

    public int ArticlePhotoId { get; set; }

    //Common Photo property
    //One article has one photo
    public Photo ArticlePhoto { get; set; }

}

你的照片对象看起来是正确的 CenterId 它下面的线删除了 virtual

在您的 Center 对象中,使用 ICollection 而不是 List

其余的应该只是自动映射而不需要配置文件。

编辑: 关于 virtual 如果您使用的是延迟加载,那么它似乎是受支持的,但是需要配置来设置它。我会先让事情尽可能简单,然后验证它是否有效,然后添加延迟加载。

参考: