-2

I keep getting an error and I can't figure out the source of it. I'm trying to do a simple image upload connected to an item and when trying to pull the list I get the following error:

The entity or complex type ' ' cannot be constructed in a LINQ to Entities query

public ActionResult Index()
{
    var content = db.Items.Select(s => new
    {
        s.Id,
        s.Image,
        s.Price,
        s.Quantity,
    });

    List<Item> contentModel = content.Select(item => new Item()
    {
        Id = item.Id,
        Image = item.Image,
        Price = item.Price,
        Quantity = item.Quantity,
    }).ToList();

    return View(contentModel);
}
Timmer
  • 3
  • 3
  • What is the type of `Image`? – Dai Feb 13 '17 at 08:10
  • Image is a byte[] – Timmer Feb 13 '17 at 08:11
  • 3
    Why is your code performing a `Select` to a new anonymous type and then taking it directly to `new Item`? Why not go directly: `db.Items.Select( s => new Item() { ... })`? – Dai Feb 13 '17 at 08:11
  • Sorry could you explain a bit more this is my first attempt at this – Timmer Feb 13 '17 at 08:13
  • 1
    In LINQ to Entities you cannot project to an existing entity type but only to an anonymous type or a regular class. – Felipe Cruz Feb 13 '17 at 08:15
  • Possible duplicate of [The entity or complex type ' ' cannot be constructed in a LINQ to Entities query](http://stackoverflow.com/questions/12916080/the-entity-or-complex-type-cannot-be-constructed-in-a-linq-to-entities-query) – Manfred Radlwimmer Feb 13 '17 at 08:18
  • What is the point of this? Why not just use `var content = db.Items.ToList()`? –  Feb 13 '17 at 08:38

1 Answers1

0

If your data-source is a SQL database you have to call ToList before you call Select with a Expression that is non translatable into SQL.

content.ToList().Select(...)
Michael Mairegger
  • 6,833
  • 28
  • 41