简体   繁体   中英

Entity Framework mapping of 3 tables with relationship between each other

Here's my problem: I have 3 tables in my database

  1. Movies (list of movies)

    • ID
    • OriginalTitle ...
  2. Genres (table with all possible genres)

    • ID
    • Name
  3. RelatedGenres (those genres that belog to a specific movie and point a specific genre, since movie can have more than 1 genre)

    • ID
    • MovieID
    • GenreID

The relationships are as folows:

Movies.ID -> RelatedGenres.MovieID -> Genres.ID

I have a model with assosiations (navigation properties). What I get:

class Movie
{
   public int ID { get; set; }
   public string OriginalTitle { get; set; }
   public ObjectCollection<RelatedGenre> RelatedGenres { get; set; }
}

where

class RelatedGenre
{
   public int ID { get; set; }
   public int MovieID { get; set; }
   public ObjectCollection<Genre> Genres { get; set; }
}

What I want:

class Movie
{
   public int ID { get; set; }
   public string OriginalTitle { get; set; }
   public ObjectCollection<Genre> Genres { get; set; }
}

As you can see, i want to skip data from this array of RelatedGenres & just get array of concrete Genres...

How can I achive this? Thanks in advance =)

You need to remove th ID column of the RelatedGenres table. The join table of many-to-many relationship should only contain the keys of the participating entities.

EF will automatically model the relationship as you have shown in the final code sample.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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