Using Dynamic Navigation Property or BaseEntity in EF Code First

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

Question

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

}  
1
0
2/14/2019 2:21:23 PM

Accepted Answer

At first glance, if you are using Entity Framework Core... don't use virtual

so your Article object should look like this

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

in your Center object, use ICollection instead of 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. 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?

0
2/14/2019 3:29:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow