EF Code First - Linq to Entities Union EqualityComparer

♀尐吖头ヾ 提交于 2020-01-04 04:14:30

问题


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

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

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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/6068575/ef-code-first-linq-to-entities-union-equalitycomparer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!