In the previous post we ended up with entities that hide the join entity from the public surface. However, it was not possible to add or removed entities through this public surface. To enable this we need an ICollection implementation that acts as a true facade over the real join entity collection and delegates all responsibilities to that collection.

The collection implementation

Here’s one possible implementation of such a collection:

public class JoinCollectionFacade<T, TJoin> : ICollection<T>
{
private readonly ICollection<TJoin> _collection;
private readonly Func<TJoin, T> _selector;
private readonly Func<T, TJoin> _creator; public JoinCollectionFacade(
ICollection<TJoin> collection,
Func<TJoin, T> selector,
Func<T, TJoin> creator)
{
_collection = collection;
_selector = selector;
_creator = creator;
} public IEnumerator<T> GetEnumerator()
=> _collection.Select(e => _selector(e)).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator(); public void Add(T item)
=> _collection.Add(_creator(item)); public void Clear()
=> _collection.Clear(); public bool Contains(T item)
=> _collection.Any(e => Equals(_selector(e), item)); public void CopyTo(T[] array, int arrayIndex)
=> this.ToList().CopyTo(array, arrayIndex); public bool Remove(T item)
=> _collection.Remove(
_collection.FirstOrDefault(e => Equals(_selector(e), item))); public int Count
=> _collection.Count; public bool IsReadOnly
=> _collection.IsReadOnly;
}

The idea is pretty simple–operations on the facade are translated into operations on the underlying collection. Where needed, a “selector” delegate is used to extract the desired target entity from the join entity. Likewise, a “creator” delegate creates a new join entity instance from the target entity when a new relationship is added.

实际上我觉得改成下面这样会更好,另外Remove和Contains方法我觉得没什么用,所以暂时就先放的抛出NotSupportedException异常:

public class ActionCollection<T, TJoin> : ICollection<T>
{
protected readonly Func<T, TJoin> creator;
protected readonly Func<TJoin, T> selector;
protected readonly Func<ICollection<TJoin>> collectionSelector; public ActionCollection(Func<ICollection<TJoin>> collectionSelector, Func<T, TJoin> creator, Func<TJoin, T> selector)
{
this.collectionSelector = collectionSelector;
this.creator = creator;
this.selector = selector;
} public int Count => collectionSelector().Count; public bool IsReadOnly => collectionSelector().IsReadOnly; public void Add(T item)
{
collectionSelector().Add(creator(item));
} public void Clear()
{
collectionSelector().Clear();
} public bool Contains(T item)
{
throw new NotSupportedException("Contains is not supported");
} public void CopyTo(T[] array, int arrayIndex)
{
List<T> list = new List<T>(); foreach (var tJoin in collectionSelector())
{
list.Add(selector(tJoin));
} list.CopyTo(array, arrayIndex);
} public IEnumerator<T> GetEnumerator()
{
return this.collectionSelector().Select(tj => this.selector(tj)).GetEnumerator();
} public bool Remove(T item)
{
throw new NotSupportedException("Remove is not supported");
} IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}

Updating the model

We need to initialize instances of this collection in our entities:

public class Post
{
public Post()
=> Tags = new JoinCollectionFacade<Tag, PostTag>(
PostTags,
pt => pt.Tag,
t => new PostTag { Post = this, Tag = t }); public int PostId { get; set; }
public string Title { get; set; } private ICollection<PostTag> PostTags { get; } = new List<PostTag>(); [NotMapped]
public ICollection<Tag> Tags { get; }
} public class Tag
{
public Tag()
=> Posts = new JoinCollectionFacade<Post, PostTag>(
PostTags,
pt => pt.Post,
p => new PostTag { Post = p, Tag = this }); public int TagId { get; set; }
public string Text { get; set; } private ICollection<PostTag> PostTags { get; } = new List<PostTag>(); [NotMapped]
public ICollection<Post> Posts { get; }
}

Using the ICollection navigations

Notice how Tags and Posts are now ICollection properties instead of IEnumerable properties. This means we can add and remove entities from the many-to-many collections without using the join entity directly. Here’s the test application updated to show this:

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" }
}; posts[].Tags.Add(tags[]);
posts[].Tags.Add(tags[]);
posts[].Tags.Add(tags[]);
posts[].Tags.Add(tags[]);
posts[].Tags.Add(tags[]);
posts[].Tags.Add(tags[]);
posts[].Tags.Add(tags[]);
posts[].Tags.Add(tags[]); context.AddRange(tags);
context.AddRange(posts); 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 oldTag = post.Tags.FirstOrDefault(e => e.Text == "Pineapple");
if (oldTag != null)
{
post.Tags.Remove(oldTag);
post.Tags.Add(newTag1);
}
post.Tags.Add(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;
}
}

Notice that:

  • When seeding the database, we add Tags directly to the Tags collection on Post.
  • When finding and removing existing tags, we can search directly for the Tag and remove it from the Post.Tags collection without needing to use the join entity.

It’s worth calling out again that, just like in the previous post, we still can’t use Tags directly in any query. For example, using it for Include won’t work:

var posts = context.Posts
.Include(e => e.Tags) // Won't work
.ToList();

EF has no knowledge of “Tags”–it is not mapped. EF only knows about the private PostTags navigation property.

Functionally, this is about as far as we can go without starting to mess with the internals of EF. However, in one last post I’ll show how to abstract out the collection and join entity a bit more so that it is easier reuse for different types.

原文链接

Many-to-many relationships in EF Core 2.0 – Part 3: Hiding as ICollection的更多相关文章

  1. 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. ...

  2. Many-to-many relationships in EF Core 2.0 – Part 1: The basics

    转载这个系列的文章,主要是因为EF Core 2.0在映射数据库的多对多关系时,并不像老的EntityFramework那样有原生的方法进行支持,希望微软在以后EF Core的版本中加入原生支持多对多 ...

  3. 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 ...

  4. EF Core 1.0 和 SQLServer 2008 分页的问题

    EF Core 1.0 在sqlserver2008分页的时候需要指定用数字分页. EF Core1.0 生成的分页语句中使用了 Featch Next.这个语句只有在SqlServer2012的时候 ...

  5. 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 ...

  6. EF Core 1.0中使用Include的小技巧

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:由于EF Core暂时不支持Lazy Loading,所以利用Include来加载额外 ...

  7. .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 ...

  8. EF Core 2.0 新特性

    前言 目前 EF Core 的最新版本为 2.0.0-priview1-final,所以本篇文章主要是针对此版本的一些说明. 注意:如果你要在Visual Studio 中使用 .NET Core 2 ...

  9. 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 ...

随机推荐

  1. docker 容器启动并自启动redis

    centos7.5 背景:每次开机后都要自动启动redis,也就是宿主机开机,启动容器,然后启动redis 按照网上的做法是:修改redis.conf ,修改redis的启动脚本(utils/...s ...

  2. FWORK-数据存储篇 -- 范式与反模式 (学习和理解)

    理解 1.第二范式的侧重点是非主键列是否完全依赖于主键,还是依赖于主键的一部分.第三范式的侧重点是非主键列是直接依赖于主键,还是直接依赖于非主键列.  2. 反模式 范式可以避免数据冗余,减少数据库的 ...

  3. mysql 笔记3

    --建库create database dsdb DEFAULT CHARACTER set utf8 collate utf8_general_ci;/*删除数据库drop DATABASE 数据库 ...

  4. JQuery总结摘要

    一 概述 1.JQuery是什么? JQuery是一个JavaScript库,简化了JS操作,扩展了JS功能. 2.分离原则 JQuery遵循导入与使用分离的原则,即使用一个<script> ...

  5. mongoDB (mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)

    MongoDB - 简介 官网:https://www.mongodb.com/ MongoDB 是一个基于分布式文件存储的数据库,由 C++ 语言编写,旨在为 WEB 应用提供可扩展的高性能数据存储 ...

  6. ASP.NET内容页中访问母版页中的对象

    在ASP.NET2.0开始,提供了母版页的功能.母版页由一个母版页和多个内容页构成.母版页的主要功能是为ASP.NET应用程序中的页面创建相同的布局和界面风格.母版页的使用与普通页面类似,可以在其中放 ...

  7. KNN 与 K - Means 算法比较

    KNN K-Means 1.分类算法 聚类算法 2.监督学习 非监督学习 3.数据类型:喂给它的数据集是带label的数据,已经是完全正确的数据 喂给它的数据集是无label的数据,是杂乱无章的,经过 ...

  8. 抖音C#版,自己抓第三方抖音网站

    感谢http://dy.lujianqiang.com技术支持 文章更新:http://dy.lujianqiang.com这个服务器已经关了,现在没用了 版权归抖音公司所有,该博客只是为交流学习所使 ...

  9. JDBC mysql驱动

    在用JDBC连接MySQL数据库时,需要使用驱动 mysql-connector-java-5.1.41-bin.jar 在本地java应用程序中,只需将jar包导入到项目library中即可, 而在 ...

  10. 微信小程序——代码构成

    通过上一章讲解,我们了解到如何初始化一个小程序项目,这里是官方给到demo地址,通过demo来看教程更方便于我们理解项目架构. 由四种文件构成: .json 后缀的 JSON 配置文件 .wxml 后 ...