今天在博问中看到一个关于 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 tag = new Tag
{
TagName = "efcore"
}; var post = new Post
{
Title = "test title",
Content = "test body"
}; var postTag = new PostTag
{
Tag = tag,
Post = post
}; writeDbContext.Add(postTag);
writeDbContext.SaveChanges(); var readDbContext = sp.GetService<MyDbContext>();
var queryPost = await readDbContext.Posts
.Include(p => p.PostTags)
.ThenInclude(pt => pt.Tag)
.FirstOrDefaultAsync();
Console.WriteLine(queryPost.PostTags[].Tag.TagName);
}
}

查询时需要使用 ThenInclude ,但这里使用 ThenInclude 时 VS2017 的智能感知有个bug ,pt.Tag 感知不出来,详见 Include->ThenInclude for a collection 。

如果使用 SQL Server ,会生成下面的 SQL 语句:

SELECT TOP(1) [p].[PostId], [p].[Content], [p].[Title]
FROM [Posts] AS [p]
ORDER BY [p].[PostId]
SELECT [p.PostTags].[PostId], [p.PostTags].[TagId], [p.Tag].[TagId], [p.Tag].[TagName]
FROM [PostTag] AS [p.PostTags]
INNER JOIN [Tags] AS [p.Tag] ON [p.PostTags].[TagId] = [p.Tag].[TagId]
INNER JOIN (
SELECT TOP(1) [p0].[PostId]
FROM [Posts] AS [p0]
ORDER BY [p0].[PostId]
) AS [t] ON [p.PostTags].[PostId] = [t].[PostId]
ORDER BY [t].[PostId]

初试 Entity Framework Core 的多对多映射的更多相关文章

  1. Entity Framework Core 生成跟踪列

    本文翻译自<Entity Framework Core: Generate tracking columns>,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! 注意:我使用的是 ...

  2. Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 读取关系数据

    Reading related data¶ 9 of 9 people found this helpful The Contoso University sample web application ...

  3. Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 创建复杂数据模型

    Creating a complex data model 创建复杂数据模型 8 of 9 people found this helpful The Contoso University sampl ...

  4. Entity Framework Core 2.0 入门简介

    不多说废话了, 直接切入正题. EF Core支持情况 EF Core的数据库Providers: 此外还即将支持CosmosDB和 Oracle. EFCore 2.0新的东西: 查询: EF.Fu ...

  5. Entity Framework Core 2.0 入门

    该文章比较基础, 不多说废话了, 直接切入正题. 该文分以下几点: 创建Model和数据库 使用Model与数据库交互 查询和保存关联数据 EF Core支持情况 EF Core的数据库Provide ...

  6. Entity Framework Core 1.1 升级通告

    原文地址:https://blogs.msdn.microsoft.com/dotnet/2016/11/16/announcing-entity-framework-core-1-1/ 翻译:杨晓东 ...

  7. 全自动迁移数据库的实现 (Fluent NHibernate, Entity Framework Core)

    在开发涉及到数据库的程序时,常会遇到一开始设计的结构不能满足需求需要再添加新字段或新表的情况,这时就需要进行数据库迁移. 实现数据库迁移有很多种办法,从手动管理各个版本的ddl脚本,到实现自己的mig ...

  8. Entity Framework Core 1.1 Preview 1 简介

    实体框架核心(EF Core)是Entity Framework的一个轻量级,可扩展和跨平台版本. 10月25日,Entity Framework Core 1.1 Preview 1发布了. 升级到 ...

  9. 创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

    创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表 创建数据模型类(POCO类) 在Models文件夹下添 ...

随机推荐

  1. TCMalloc小记(转)

    一. 原理 tcmalloc就是一个内存分配器,管理堆内存,主要影响malloc和free,用于降低频繁分配.释放内存造成的性能损耗,并且有效地控制内存碎片.glibc中的内存分配器是ptmalloc ...

  2. Vue加载组件、动态加载组件的几种方式

    https://cn.vuejs.org/v2/guide/components.html https://cn.vuejs.org/v2/guide/components-dynamic-async ...

  3. django --- DetailView源码分析

    [背景] 最近在看django官方文档的class-based-views这一节的时候一直不得要领,感觉自己清楚,但是回想起来又没有脉络:于是没有办法只 能是“暗中观察”django的源码了. 刚打开 ...

  4. 2D空间中求两圆的交点

    出处:https://stackoverflow.com/questions/19916880/sphere-sphere-intersection-c-3d-coordinates-of-colli ...

  5. android 推流解决方案

    .LocalSocket + MediaRecorder + librtmp

  6. c++命名空间---namespace

    C++ 命名空间 C++ 应用程序中.例如,您可能会写一个名为 func() 的函数,在另一个可用的库中也存在一个相同的函数 func().这样,编译器就无法判断您所使用的是哪一个 func() 函数 ...

  7. django DateTimeField 时间格式化

    ['%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # ' ...

  8. 【iCore1S 双核心板_ARM】例程二:读取ARM按键状态

    实验原理: 按键的一端与STM32的GPIO(PB9)相连,且PB9外接一个1k大小的限流上接电阻. 初始化时把PB9设置成输入模式,当按键弹起时,PB9由于上拉电阻的作用呈高电平(3.3V): 当按 ...

  9. Hive数据倾斜解决办法总结

    数据倾斜是进行大数据计算时最经常遇到的问题之一.当我们在执行HiveQL或者运行MapReduce作业时候,如果遇到一直卡在map100%,reduce99%一般就是遇到了数据倾斜的问题.数据倾斜其实 ...

  10. 假期小结 BIO, NIO, AIO

    虽然忙碌,但仍小有收获,开心. 引子 BIO: Blocking IO,阻塞式IO NIO: Non-blocking IO,非阻塞式IO AIO: Async IO,异步IO 问题 什么是阻塞式IO ...