EF代码优先-Linq to Entities Union EqualityComparer [英] EF Code First - Linq to Entities Union EqualityComparer

查看:83
本文介绍了EF代码优先-Linq to Entities Union EqualityComparer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要合并的IEnumerable集合.

I have two IEnumerable collections that I would like to union.

一个选择与特定类别关联的新闻对象.当用户按类别进行过滤时,我还希望显示已被另一个类别标记的新闻文章.

One selects news objects that are associated with a particular category. When a user is filtering by a category I would also like news articles that have been tagged with another category to be displayed.

因此,我还有另一个查询,该查询返回带有特定子类别标记的新闻对象.

So I have another query that returns news objects that are tagged with the particular sub category.

现在,我想合并两个收藏集,删除重复项(作为与主要类别相关的新闻,也可以在第二个类别中进行标记).

Now I would like to union the two collections, removing duplicates (as a news article associated to the main category, may also be tagged with the second category).

 var catNews = model.Category.News.SelectMany(n => n.News); //get news article associated to the category
 var tagNews = _nr.GetNews(model.Category.relatedCategoryName); //this selects news by tags - which I want as the related category name
 model.News = catNews.Union(tagNews).OrderByDescending(p => p.Date); //union the two collections

但是,model.News现在包含两个相同的新闻文章,我不确定为什么工会应该使用默认的相等比较器?

However, model.News now contains two identical news articles and I am not sure why as union should use the default equality comparer?

我在这里做错什么了吗?我正在使用EF Code First,我的主键是新闻ID.

Am I doing something wrong here? I am using EF Code First and my primary key is the news id.

解决这个问题的方法是将catNews id的列表传递给GetNews函数并将其排除

The way I have got round this issue is by passing in a list of the catNews id to the GetNews function and excluding them

if (excludeIds != null)
    q = q.Where(n => !excludeIds.Contains(n.ID));

但是我不确定为什么我以为工会会删除相同的文章时为什么要这样做?

But I am not sure why I have to this when I thought union would remove the identical articles?

推荐答案

我猜您不是从实体框架上下文的同一实例加载这两个集合.默认的相等比较器将比较引用,并且如果您使用相同的上下文,则当Id匹配时,它的确会在两个集合中返回相同的News实例,但是如果您使用不同的上下文,则每个集合将包含其自己的News实例和Concat相同.在这种情况下,您必须覆盖News实体中的Equals(和GetHaschCode)以比较Id或使用自定义比较器.

I guess that you are not loading these two collections from the same instance of the entity framework context. Default equality comparer will compare references and if you use the same context it will indeed return same News instance in both collections when Id is matching but if you use different contexts each collection will contain its own News instances and Union will do the same as Concat. In such case you must override Equals (and GetHaschCode) in your News entity to compare Id or use custom comparer.

这篇关于EF代码优先-Linq to Entities Union EqualityComparer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆