Easy join tables with EF Code First.

Entity Framework Code First is getting even better, release after release. Here’s how to easily get a many to many relationship between two entities. Not to much to do really, once the relationship is specified within the two classes (an ICollection navigation property for each of the two ends in the relation), EF will take care of creating a join table.

Code Snippet
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; }
}

 

Code Snippet
[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();
}

image




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *