EF Code First - Linq to Entities Union EqualityComparer
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?
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.
精彩评论