【问题标题】:Using Dynamic Navigation Property or BaseEntity in EF Code First在 EF Code First 中使用动态导航属性或 BaseEntity
【发布时间】:2019-02-14 14:21:23
【问题描述】:

这个问题可能很简单,但逻辑很重要,我对此感到困惑。在带有实体框架核心代码的 Asp.Net Core 2.1 中,我想学习如何建模,所以我简化了这个问题。两个不同实体(中心和文章)中的一个相同导航属性(照片)。中心可以有很多照片,文章可以有一张照片。一张照片可以有一个帖子或一个中心,因此也可以有一个 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; }

}  

【问题讨论】:

    标签: c# asp.net-core ef-code-first entity-framework-core


    【解决方案1】:

    乍一看,如果您使用的是 Entity Framework Core……请不要使用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,如果您使用延迟加载,那么它似乎受支持,但需要进行配置才能进行设置。我会先让事情尽可能简单,然后验证它是否有效,然后添加延迟加载。

    参考:navigation property should be virtual - not required in ef core?

    【讨论】:

    • 我已经按照您说的进行了编辑,并且有效。但实际上,我无法清楚地理解这个主题。在数据库结构中;照片表有 centerid 字段,但没有 postid。正常吗?为什么?中心表没有 photoid 字段,所以我认为它看起来很正常,因为它的收藏。但是 post 表没有 photoid 字段。它看起来很奇怪还是正常?谢谢。
    • @Aykarnz 您的 Post 对象是什么样的?我在做一个假设,但是您的 Post 是否有多张照片,所以它是一个 ICollection ......可能有另一个表由 EF 创建,它从 Posts 和 Photos 中获取外键......就像 PostPhoto 或 PhotoPost 表。在这种结构中,您可以拥有多张相互关联的照片和帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2016-01-09
    • 2016-10-10
    相关资源
    最近更新 更多