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

前端 未结 4 1490
离开以前
离开以前 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:02

    I would suggest you to go with the simpler approach of creating another model ArtistGenre and let EF figure out the relationship on its own. Create the table as below.

    public class ArtistGenre
    {
        public int Id;
        public int GenreId;
        public int ArtistId;
    
        public virtual Genre Genre;
        public virtual Artist Artist;
    }
    

    After that you will have another table added to the database by the above name with two foriegn key properties and one primary key.

    Now, you can run the queries on this table. Say

    var artist = myContext.ArtistGenre.where( g = g.GenreId == 1).ToList();
    

    Now, artist wil hold all the artist under Genre with Id =1. You can do the vice-versa for Genres too in the similar way.

    Hope it helps !!

提交回复
热议问题