Question

This is my code:

var query = context.SomeEntities.Select(e => new SomeDto
{
    Name = e.Title,       
})

The variable query is IQueryable.

var list = new List<SomeDto>
{
    new SomeDto
    {
          Name = "SomeName1"      
    },
    new SomeDto
    {
          Name = "SomeName2"      
    }
};

Now I need union these collections,I write

query = query.Union(list)

But in this place I get exception

Unable to create a constant value of type 'SomeDto'. Only primitive types or enumeration types are supported in this context

I know that I can do ToList() for first collection,but I need union collections without call to database.How can I do this?

1
1
11/11/2014 6:51:05 AM

Popular Answer

As user3825493 pointed, there are answers regarding similar issues. The first link pretty much explains the whole thing.

Your problem is that due to the fact that Union is mapped to SQL UNION, arguments of the operation are to be converted to data types acceptable by Entity Framework. However, the only types acceptable by it for items inside IEnumerable input parameters are, as specified in the error you get, primitive types and enum's.

You should either:

var unionOfQueryWithList = query.AsEnumerable().Union(list)

or, if you like to use the SQL facilities, write a stored procedure which performs the union as part of its logic and find the way to pass your data into SQL, such as this.

The former loads all the results of the query into a memory before performing the union. It is convenient for the cases when you have all the pre-filtered data returned from EF and only want to use the output for later processing in your code.

The later takes you out of the EF zone and required for the cases when you have operations which will benefit from running on SQL engine, such as filtering or joining DB data based on a complex data you have access to in your code.

1
5/23/2017 10:26:42 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow