nam nam - 3 months ago 28
C# Question

LINQ Union causing error if a column in the query is DateTime

I'm getting the following error in UNION of two LINQ queries:

'IQueryable<<anonymous type: string CustName, DateTime? ModifiedDate>>' does not contain a definition for 'Union'......


Models:

Public class Customer
{
public string CustName{ get; set; }
public DateTime? DateModified{ get; set; }
}

Public class Employee
{
public string EmplName{ get; set; }
public DateTime? DateModified{ get; set; }
}


UNION Query:

var Query1 = (from c in Customers
select new {c.CustName, c.DateModified}).Union((from e in Employees
select new {e.EmplName, e.DateModified}));


NOIE: The error does not occur if I remove
c.DateModified
and
e.DateModified
from the query.

Answer

You have changed the name of the property in the second anonymous type and therefore the compiler will construct two distinct types in your query. You have to pick one name for the customer/employee name in both cases, for instance:

var Query1 = (from c in Customers
               select new {Name = c.CustName, c.DateModified}).Union((from e in Employees
               select new {Name = e.EmplName, e.DateModified}));

In general, it is advised to avoid letting the compiler figure property names in anonymous types. That is what leads to errors, e.g. when you refactor later and change name of some property, like EmplName. That change automatically affects the anonymous type in which EmplName was used to assign value to the property. Therefore, it would be better to be absolutely explicit about property names, like:

var Query1 = (from c in Customers
               select new {Name = c.CustName, Date = c.DateModified})
    .Union((from e in Employees
               select new {Name = e.EmplName, Date = e.DateModified}));

When done this way, compiler will construct exactly one type for both anonymous types used above. That type would have properties Name and Date (in that specific order - even the changed order of names causes a new type to be generated). And then Union extension method would be there because both sequences you are uniting are of the same type.

Comments