EF Code-First: many-to-many navigation in one direction

I am trying to create the first code model in which a Person can have many favorite films, but I do not want FK to be in the Movies table.

The only way to achieve this is to get EF to create a link table between the two objects, and for that (afaik) I have a collection property in the Movies object related 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 the movie to look like this ...

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

But at the same time, EF will not create a link table, it will simply hit the Person_Id FK column in the Movies table.

I do not want this to happen, because films should not have anything to do with people, and I could connect them with something else.

So how do I get a cake and eat it?

+4
source share
1 answer

Must. 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 where the entry 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 an excerpt from: http://george2giga.com/2012/05/02/easy-join-tables-with-ef-code-first/

+1
source

Source: https://habr.com/ru/post/1416604/


All Articles