今天在博问中看到一个关于 EF Core 的提问 ef core 2.0 多对多查询的问题,由于还没使用过 EF Core 的多对多映射,于是参考 EF Core 帮助文档快速写了个 .net core 控制台程序(基于 EF Core In-Memory Database)实验了一下。
实体类的定义:
1)Post
public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public List<PostTag> PostTags { get; set; } }
2)Tag
public class Tag { public int TagId { get; set; } public string TagName { get; set; } public List<PostTag> PostTags { get; set; } }
3)PostTag
public class PostTag { public int PostId { get; set; } public Post Post { get; set; } public int TagId { get; set; } public Tag Tag { get; set; } }
DbContext 的定义与映射配置:
public class MyDbContext : DbContext { public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } 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); } }
控制台程序 Main 方法:
class Program { static async Task Main(string[] args) { IServiceCollection services = new ServiceCollection(); services.AddDbContext<MyDbContext>(options => { options.UseInMemoryDatabase("blog_sample"); }); IServiceProvider sp = services.BuildServiceProvider(); var writeDbContext = sp.GetService<MyDbContext>(); var post = new Post { Title = "test title", Content = "test body", PostId = 1 }; writeDbContext.Add(post); var tag = new Tag { TagId = 2, TagName = "efcore" }; writeDbContext.Add(tag); var postTag = new PostTag { PostId = 1, TagId = 2 }; writeDbContext.Add(postTag); writeDbContext.SaveChanges(); var readDbContext = sp.GetService<MyDbContext>(); post = await readDbContext.Posts.FirstOrDefaultAsync(); Console.WriteLine(post.PostTags.FirstOrDefault().Tag.TagId); //output is 2 } }
查询时连 Include 都不需要,EF Core 会自动打理好一切。