Created
January 28, 2013 13:50
-
-
Save jayhjkwon/4655633 to your computer and use it in GitHub Desktop.
many-to-many configuration using Entity Framework Code First
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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