简体   繁体   English

首先在EF代码中使用动态导航属性或BaseEntity

[英]Using Dynamic Navigation Property or BaseEntity in EF Code First

This question may be simple, but the logic is important and I'm confused about it. 这个问题可能很简单,但是逻辑很重要,对此我感到困惑。 In Asp.Net Core 2.1 with Entity Framework Core Code First, I want to learn how to model, so i have simplified the problem. 在带有实体框架核心代码的Asp.Net Core 2.1中,我想学习如何建模,因此我简化了这个问题。 One same navigation property (Photo) in two different entity (Center and Article). 两个不同实体(中心和文章)中的一个相同导航属性(照片)。 Center can has many photos and article can has one photo. 中心可以有很多照片,文章可以有一张照片。 A photo can has one post or one center, so can has one MyEntityBase. 一张照片可以有一个帖子或一个中心,所以可以有一个MyEntityBase。 Example: 例:

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; }

}  

At first glance, if you are using Entity Framework Core... don't use virtual 乍一看,如果您使用的是Entity Framework Core ...请不要使用virtual

so your Article object should look like this 所以您的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; }

}

your photo object looks correct with the CenterId the line below it remove the virtual 您的照片对象使用CenterId正确显示,其CenterId的行删除了virtual

in your Center object, use ICollection instead of List 在您的Center对象中,使用ICollection而不是List

the rest should just map automatically without a configuration file. 其余的应该只是自动映射而无需配置文件。

Edit: On regards to virtual if you are using lazy loading then it seems to be supported, but configuration is needed to set that up. 编辑:关于virtual如果您正在使用延迟加载,则似乎支持该功能,但需要进行配置才能进行设置。 I'd keep things as simple as possible first and verify that it works then add lazy loading. 我将首先使事情尽可能简单,然后验证它是否有效,然后添加延迟加载。

reference: navigation property should be virtual - not required in ef core? 参考: 导航属性应该是虚拟的-ef核心中不需要吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM