Skip to content

Instantly share code, notes, and snippets.

@jayhjkwon
Created January 28, 2013 13:50
Show Gist options
  • Save jayhjkwon/4655633 to your computer and use it in GitHub Desktop.
Save jayhjkwon/4655633 to your computer and use it in GitHub Desktop.
many-to-many configuration using Entity Framework Code First
public class BlogContext : DbContext
{
public BlogContext()
{
}
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>()
.HasMany(p => p.Tags)
.WithMany(t => t.Posts)
.Map(m =>
{
m.ToTable("TagPosts");
m.MapLeftKey("PostId");
m.MapRightKey("TagId");
});
}
}
public class Post
{
public Post()
{
this.Tags = new List<Tag>();
}
public int Id { get; set; }
[Required]
[MaxLength(125)]
public string Title { get; set; }
[Required]
public string Content { get; set; }
public DateTime DateCreated { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public Tag()
{
this.Posts = new List<Post>();
}
public int Id { get; set; }
[MaxLength(125)]
public string TagText { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment