mortware
mortware

Reputation: 1940

EF Code-First: Many-to-many with one direction navigation

I'm trying to create a code-first model where a Person can have many favourite Movies, but I don't want a FK in the Movies table.

The only way to achieve this, is to get EF to create a link table between the two entities, and to do that (afaik) I have create a collection property on the Movies entity relating to Person...

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual IList<Movie> FavouriteMovies { get; set; }
}

public class Movie
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IList<Person> People { get; set; } // I don't want this here :(
}

I want Movie to look like this...

public class Movie
{
    public int Id { get; set; }
    public string Name { get; set; }
}

But in doing that, the EF won't create a link table, it will just whack a Person_Id FK column in the Movies table.

I don't want this to happen, as Movies shouldn't have anything to do with People, and I might want to relate it to something else.

So how do I have my cake and eat it?

Upvotes: 4

Views: 767

Answers (1)

Giorgio Minardi
Giorgio Minardi

Reputation: 2775

It should. How do you add your entities ? Here's a sample:

public class Character : BaseEntity
{
    public string Name { get; set; }
    public bool IsEvil { get; set; }
    public virtual ICollection<Videogame> Videogames { get; set; } 
}
public class Videogame : BaseEntity 
{
    public string Name { get; set; }
    public DateTime ReleasedDate { get; set; }
    public virtual ICollection<Character> Characters { get; set; }
    public Author Author { get; set; }
}

Here's where the record is added :

[Test]
public void CreateJoinTable()
{
    var character = new Character() {Name = "Wario", IsEvil = true};
    var videogame = new Videogame() {Name = "Super Mario Bros 20", ReleasedDate = DateTime.Now , Characters = new Collection<Character>()};
    videogame.Characters.Add(character);
    var context = new NerdContext();
    context.Add(videogame);
    context.SaveAllChanges();
}

Here's where the snippet come from : http://george2giga.com/2012/05/02/easy-join-tables-with-ef-code-first/

Upvotes: 1

Related Questions