vcRobe
vcRobe

Reputation: 1781

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?

Upvotes: 14

Views: 950

Answers (3)

Servy
Servy

Reputation: 203848

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.

Upvotes: 2

SMS
SMS

Reputation: 462

Try this:

struct MyStruct
{
            public string name;
            public double amount;
}

Products[] p1 = new Products[] { new Products { name = "prod1", amount = 5 }
var c = from p in p1
        select new MyStruct { name = p.name, amount = p.amount };

Upvotes: -1

Shlomo
Shlomo

Reputation: 14370

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
    };

Upvotes: 3

Related Questions