Many-to-many relationships in EF Core 2.0 – Part 2: Hiding as IEnumerable
In the previous post we looked at how many-to-many relationships can be mapped using a join entity. In this post we’ll make the navigation properties to the join entity private so that they don’t appear in the public surface of our entity types. We’ll then add public IEnumerable properties that expose the relationship for reading without reference to the join entity.
Updating the model
In the first post our entity types that look like this:
public class Post
{
public int PostId { get; set; }
public string Title { get; set; } public ICollection<PostTag> PostTags { get; } = new List<PostTag>();
} public class Tag
{
public int TagId { get; set; }
public string Text { get; set; } public ICollection<PostTag> PostTags { get; } = new List<PostTag>();
}
But really we want our entity types to look more like this:
public class Post
{
public int PostId { get; set; }
public string Title { get; set; } public ICollection<Tag> Tags { get; } = new List<Tag>();
} public class Tag
{
public int TagId { get; set; }
public string Text { get; set; } public ICollection<Post> Posts { get; } = new List<Post>();
}
One way to do this is to make the PostTags navigation properties private and add public IEnumerable projections for their contents. For example:
public class Post
{
public int PostId { get; set; }
public string Title { get; set; } private ICollection<PostTag> PostTags { get; } = new List<PostTag>(); [NotMapped]
public IEnumerable<Tag> Tags => PostTags.Select(e => e.Tag);
} public class Tag
{
public int TagId { get; set; }
public string Text { get; set; } private ICollection<PostTag> PostTags { get; } = new List<PostTag>(); [NotMapped]
public IEnumerable<Post> Posts => PostTags.Select(e => e.Post);
}
Configuring the relationship
Making the navigation properties private presents a few problems. First, EF Core doesn’t pick up private navigations by convention, so they need to be explicitly configured:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PostTag>()
.HasKey(t => new { t.PostId, t.TagId }); modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Post)
.WithMany("PostTags"); modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Tag)
.WithMany("PostTags");
}
Using Include
Next, the Include call can no longer easily access to the private properties using an expression, so we use the string-based API instead:
var posts = context.Posts
.Include("PostTags.Tag")
.ToList();
Notice here that we can’t just Include tags like this:
var posts = context.Posts
.Include(e => e.Tags) // Won't work
.ToList();
This is because EF has no knowledge of “Tags”–it is not mapped. EF only knows about the private PostTags navigation property. This is one of the limitations I called out in Part 1. It would currently require messing with EF internals to be able to use Tags directly in queries.
Using the projected navigation properties
Reading the many-to-many relationship can now use the public properties directly. For example:
foreach (var tag in post.Tags)
{
Console.WriteLine($"Tag {tag.Text}");
}
But if we want to add and remove Tags we still need to do it using the PostTag join entity. We will address this in Part 3, but for now we can add a simple helper that gets PostTags by Reflection. Updating our test application to use this we get:
public class Program
{
public static void Main()
{
using (var context = new MyContext())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated(); var tags = new[]
{
new Tag { Text = "Golden" },
new Tag { Text = "Pineapple" },
new Tag { Text = "Girlscout" },
new Tag { Text = "Cookies" }
}; var posts = new[]
{
new Post { Title = "Best Boutiques on the Eastside" },
new Post { Title = "Avoiding over-priced Hipster joints" },
new Post { Title = "Where to buy Mars Bars" }
}; context.AddRange(
new PostTag { Post = posts[], Tag = tags[] },
new PostTag { Post = posts[], Tag = tags[] },
new PostTag { Post = posts[], Tag = tags[] },
new PostTag { Post = posts[], Tag = tags[] },
new PostTag { Post = posts[], Tag = tags[] },
new PostTag { Post = posts[], Tag = tags[] },
new PostTag { Post = posts[], Tag = tags[] },
new PostTag { Post = posts[], Tag = tags[] }); context.SaveChanges();
} using (var context = new MyContext())
{
var posts = LoadAndDisplayPosts(context, "as added"); posts.Add(context.Add(new Post { Title = "Going to Red Robin" }).Entity); var newTag1 = new Tag { Text = "Sweet" };
var newTag2 = new Tag { Text = "Buzz" }; foreach (var post in posts)
{
var oldPostTag = GetPostTags(post).FirstOrDefault(e => e.Tag.Text == "Pineapple");
if (oldPostTag != null)
{
GetPostTags(post).Remove(oldPostTag);
GetPostTags(post).Add(new PostTag { Post = post, Tag = newTag1 });
}
GetPostTags(post).Add(new PostTag { Post = post, Tag = newTag2 });
} context.SaveChanges();
} using (var context = new MyContext())
{
LoadAndDisplayPosts(context, "after manipulation");
}
} private static List<Post> LoadAndDisplayPosts(MyContext context, string message)
{
Console.WriteLine($"Dumping posts {message}:"); var posts = context.Posts
.Include("PostTags.Tag")
.ToList(); foreach (var post in posts)
{
Console.WriteLine($" Post {post.Title}");
foreach (var tag in post.Tags)
{
Console.WriteLine($" Tag {tag.Text}");
}
} Console.WriteLine(); return posts;
} private static ICollection<PostTag> GetPostTags(object entity)
=> (ICollection<PostTag>)entity
.GetType()
.GetRuntimeProperties()
.Single(e => e.Name == "PostTags")
.GetValue(entity);
}
This test code will be simplified significantly in the next post where we show how to make the projected navigations updatable.
Many-to-many relationships in EF Core 2.0 – Part 2: Hiding as IEnumerable的更多相关文章
- Many-to-many relationships in EF Core 2.0 – Part 3: Hiding as ICollection
In the previous post we ended up with entities that hide the join entity from the public surface. Ho ...
- Many-to-many relationships in EF Core 2.0 – Part 1: The basics
转载这个系列的文章,主要是因为EF Core 2.0在映射数据库的多对多关系时,并不像老的EntityFramework那样有原生的方法进行支持,希望微软在以后EF Core的版本中加入原生支持多对多 ...
- Many-to-many relationships in EF Core 2.0 – Part 4: A more general abstraction
In the last few posts we saw how to hide use of the join entity from two entities with a many-to-man ...
- EF Core 1.0 和 SQLServer 2008 分页的问题
EF Core 1.0 在sqlserver2008分页的时候需要指定用数字分页. EF Core1.0 生成的分页语句中使用了 Featch Next.这个语句只有在SqlServer2012的时候 ...
- ASP.NET Core 开发-Entity Framework (EF) Core 1.0 Database First
ASP.NET Core 开发-Entity Framework Core 1.0 Database First,ASP.NET Core 1.0 EF Core操作数据库. Entity Frame ...
- EF Core 1.0中使用Include的小技巧
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:由于EF Core暂时不支持Lazy Loading,所以利用Include来加载额外 ...
- .NET Core 1.0、ASP.NET Core 1.0和EF Core 1.0简介
.NET Core 1.0.ASP.NET Core 1.0和EF Core 1.0简介 英文原文:Reintroducing .NET Core 1.0, ASP.NET Core 1.0, and ...
- EF Core 2.0 新特性
前言 目前 EF Core 的最新版本为 2.0.0-priview1-final,所以本篇文章主要是针对此版本的一些说明. 注意:如果你要在Visual Studio 中使用 .NET Core 2 ...
- EF Core 2.0使用MsSql/Mysql实现DB First和Code First
参考地址 EF官网 ASP.NET Core MVC 和 EF Core - 教程系列 环境 Visual Studio 2017 最新版本的.NET Core 2.0 SDK 最新版本的 Windo ...
随机推荐
- Linux下查看Tomcat的控制台输出信息
Linux下查看Tomcat的控制台输出信息 首先使用SSH连接到数据库,然后点击window创建一个new terminal, 进入tomcat/logs/文件夹下,输出控制台信息,命令如下: cd ...
- Oracle中实现find_in_set
CREATE OR REPLACE FUNCTION FIND_IN_SET(piv_str1 varchar2, piv_str2 varchar2, p_sep varchar2 := ',') ...
- Effective C++ .33 子类的名称覆盖
#include <iostream> #include <cstdlib> using namespace std; class Base { public: int add ...
- php获取今日开始时间和结束时间
$begintime=date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y'))); $endtime=date( ...
- qt 使用qtxlsx 读写excel
https://github.com/dbzhang800/QtXlsxWriter 下载qtxlsx地址 QtXlsx is a library that can read and write Ex ...
- java音频播放器
java音频播放器备份,支持wav,mp3 都是摘抄于网络,wav播放,mp3播放 播放wav版本 包: 不需要其他jar包 代码: package com; import javax.sound.s ...
- HDFS元数据管理机制
元数据管理概述 HDFS元数据,按类型分,主要包括以下几个部分: 1.文件.目录自身的属性信息,例如文件名,目录名,修改信息等. 2.文件记录的信息的存储相关的信息,例如存储块信息,分块情况,副本个数 ...
- SQL点点滴滴_删除临时表
select into 创建的表属于临时表,判断是否存在的方法 select c_adno,c_con_no into #temp from tb_contract IF OBJECT_ID( 'te ...
- C++中protected的访问权限
关于C++中protected的访问权限的讨论已经是一个很陈旧的话题了,陈旧到大家都不愿意去讨论,觉得他见到到吃饭睡觉那么自然. 我再次读<C++ Primer>的时候,其中关于prote ...
- Congestion Avoidance in TCP
Congestion Avoidance in TCP Consequence of lack of congestion control When a popular resource is sha ...