How Model n--n relationship in EF Code First to automatically generated views work correctly?

前端 未结 4 1515
离开以前
离开以前 2021-01-11 21:20

I use EF Code First and have a problem in n-n relationship, assume we have a singer that sing in some genres, so we need this models: Artist, Genre, and ArtistsGenres, I def

4条回答
  •  忘掉有多难
    2021-01-11 22:01

    The problem is you are not explicitly loadin the Genres collection of the artist class and you do not allow EF to intercept that property access by not declaring it as virtual.

    public class Artist
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection Genres { get; set; }
    }
    

    Then when you need to access artist and the related genres you need to eager load them

    var artist = db.Artists.Include(a => a.Genres)
          .Where(a => a.Name == "Foo").SingleOrDefault()
    

    Making the Genres property virtual will allow EF to lazy load the collection if you didn't eager load it.

提交回复
热议问题