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
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>()};
    var context = new NerdContext();



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s