There are certain points we need to take into consideration while performing UNION in Entity Framework.
This is an easier way to get entities with different queries and then use Union. As shown in below example, where we are using Union to get result from Texas and Florida states.
var floridaEntity = ctx.Orders.Where(o => o.State == "Florida").Select(o => o);
var TexasEntity = ctx.Orders.Where(o => o.State == "Texas").Select(o => o);
var floridaTexas = floridaEntity.Union(TexasEntity);
Another way to use Union is shown below,
(from p in Tblpages
join pa in Tblpageactions on p.PageId equals pa.PageId
join rp in Tblrolepermissions on pa.ActionId equals rp.ActionId into jrs
from jrResult in jrs.DefaultIfEmpty()
where jrResult.RoleId == 1
select new
{
PageId = p.PageId,
PageName = p.PageName,
ActionId = pa.ActionId,
pa.ActionName
}).Union
(from p in Tblpages
join pa in Tblpageactions on p.PageId equals pa.PageId
select new
{
PageId = p.PageId,
PageName = p.PageName,
ActionId = pa.ActionId,
pa.ActionName
})
If you get an error like,
'System.Linq.IQueryable<AnonymousType#1>' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.ParallelEnumerable.Union<TSource>(System.Linq.ParallelQuery<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments
Instance argument: cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.ParallelQuery<AnonymousType#2>'
your best bet is to check, objects should have exactly the same signature to be considered identical.
Comments
Post a Comment