I've a query like this one
struct MyStruct
{
public string name;
public double amount;
}
var a =
from p in Products
select new MyStruct
{
name = p.Name,
amount = p.Amount
};
When I execute the query I get the following exception:
System.NotSupportedException {"Only parameterless constructors and initializers are supported in LINQ to Entities."}
but if I change the type of MyStruct to class then it works as expected.
Why it works with class and fail with struct?
It works with LinqToObjects. I'm guessing LinqToEntities doesn't know how to create a struct. If you do this you'll be fine:
struct MyStruct
{
public string name;
public double amount;
}
var a = Products.AsEnumerable()
.Select(p => new MyStruct
{
name = p.Name,
amount = p.Amount
};
Linq to entities does not support projecting into structs. They would have needed to design support for this into the query provider, and they simply choose not to. It would appear that they didn't see it as a valuable enough feature to support for it to be worth the development cost.
You will need to project into new class instances in your queries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With