EFcore的 基础理解<三> 多对多,唯一约束
2019-09-10 18:51 qgbo 阅读(1264) 评论(0) 编辑 收藏 举报
唯一约束,替代键。
modelBuilder.Entity<Car>() .HasAlternateKey(c => new { c.State, c.LicensePlate });
多对多,可以直接建立,在上层调用的时候比较方便。
class MyContext : DbContext { public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PostTag>() .HasKey(pt => new { pt.PostId, pt.TagId }); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Tag) .WithMany(t => t.PostTags) .HasForeignKey(pt => pt.TagId); } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public List<PostTag> PostTags { get; set; } } public class Tag { public string TagId { get; set; } public List<PostTag> PostTags { get; set; } } public class PostTag { public int PostId { get; set; } public Post Post { get; set; } public string TagId { get; set; } public Tag Tag { get; set; } }
气功波(18037675651)