这个问题可能很简单,但逻辑很重要,我对此感到困惑。在带有实体框架核心代码的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; }
}
乍一看,如果您正在使用Entity Framework Core ...请不要使用virtual
所以你的文章对象应该是这样的
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?