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?

Answers


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.


Need Your Help

How do I fix “java.lang.OutOfMemoryError at sun.misc.Unsafe.allocateMemory(Native Method)”?

java image memory graphics

I'm making a Java application that uses the Slick library to load images. However, on some computers, I get this error when trying to run the program:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.