zoukankan      html  css  js  c++  java
  • ef core中如何实现多对多的表映射关系

    文档:https://docs.microsoft.com/en-us/ef/core/modeling/relationships

     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(t => new { t.PostId, t.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; }
     }
  • 相关阅读:
    51Nod1528 加号分配
    51Nod1679 连通率
    51Nod1679 连通率
    51Nod1426 沙拉酱括号
    51Nod1426 沙拉酱括号
    51Nod1678 lky与gcd
    51Nod1556 计算
    c学习第2天
    Stopwatch秒表的使用
    数据从.txt文件中导入数据库
  • 原文地址:https://www.cnblogs.com/sky-net/p/8648834.html
Copyright © 2011-2022 走看看