首页新闻找找看学习计划

ef core中如何实现多对多的表映射关系

0
悬赏园豆:10 [已关闭问题] 关闭于 2017-01-19 17:16

ef6是有HasMany、WithMany、Map的方法可以设置多对多,ef core中找不到了,然后mapping配置类也没了?有接触过的兄弟指点下啊

Alex Huang[无形]的主页 Alex Huang[无形] | 初学一级 | 园豆:190
提问于:2017-01-19 15:36
< >
分享
所有回答(2)
0

class a{

list<b>

}

class b{

list<a>

}

class a_b{

aid;

bid;

}

entityframecore 目前只能这样完

czd890 | 园豆:7463 (大侠五级) | 2017-01-19 16:09
1

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

多对多要这么搞。。。

 1 class MyContext : DbContext
 2 {
 3     public DbSet<Post> Posts { get; set; }
 4     public DbSet<Tag> Tags { get; set; }
 5 
 6     protected override void OnModelCreating(ModelBuilder modelBuilder)
 7     {
 8         modelBuilder.Entity<PostTag>()
 9             .HasKey(t => new { t.PostId, t.TagId });
10 
11         modelBuilder.Entity<PostTag>()
12             .HasOne(pt => pt.Post)
13             .WithMany(p => p.PostTags)
14             .HasForeignKey(pt => pt.PostId);
15 
16         modelBuilder.Entity<PostTag>()
17             .HasOne(pt => pt.Tag)
18             .WithMany(t => t.PostTags)
19             .HasForeignKey(pt => pt.TagId);
20     }
21 }
22 
23 public class Post
24 {
25     public int PostId { get; set; }
26     public string Title { get; set; }
27     public string Content { get; set; }
28 
29     public List<PostTag> PostTags { get; set; }
30 }
31 
32 public class Tag
33 {
34     public string TagId { get; set; }
35 
36     public List<PostTag> PostTags { get; set; }
37 }
38 
39 public class PostTag
40 {
41     public int PostId { get; set; }
42     public Post Post { get; set; }
43 
44     public string TagId { get; set; }
45     public Tag Tag { get; set; }
46 }

 

Alex Huang[无形] | 园豆:190 (初学一级) | 2017-01-19 17:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册