Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error creating a Linq query

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?

like image 471
vcRobe Avatar asked Apr 10 '13 17:04

vcRobe


2 Answers

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
    };
like image 97
Shlomo Avatar answered Oct 03 '22 23:10

Shlomo


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.

like image 37
Servy Avatar answered Oct 03 '22 23:10

Servy