9/9/2015 3:13:23 AM

The Entity Framework makes it incredibly easy to make a UNION query. Below, we are pulling data from the Contents table that is part of my DbContext. I first pull data based on a UserId and then based on a GroupId/ParentId. I call the UNION statement from the first query and then finally call the distinct method to ensure distinct rows are returned.

//user create posts
var queryUserPosts = from contents in this._dbContext.Contents

					 where contents.UserId == userId					 

					 select contents;

//group posts that user is a part of
var queryGroupPosts = from contents in this._dbContext.Contents
					  where contents.ParentId == parentId

					  select contents;

//create union
var query = queryUserPosts.Union(queryGroupPosts).Distinct().OrderByDescending(x => x.Id);