0

here's my code and I'm hoping someone could enlighten me :

public async Task<ActionResult> Search()
{
    NameValueCollection filter = HttpUtility.ParseQueryString(Request.Params.ToString());

    string term = filter["term"];
    var query = db.ProductGraphicsCards
    .Where(pgc => pgc.GraphicsCardSKU.StartsWith(term))
    .Select(pgc => new ProductGraphicsCard()
    {
        GraphicsCardSKU = pgc.GraphicsCardSKU,
        GraphicsCardMemory = pgc.GraphicsCardMemory
    };

    var products = await query.ToListAsync();

    List<string> items = new List<string>();

    foreach (var product in products)
    {
        items.Add(product.GraphicsCardSKU + " / " + product.GraphicsCardMemory.ToString());
    }

    return Json(items, JsonRequestBehavior.AllowGet);
}

gives me an error and I can't understand why

2 Answers2

0

Here

.Select(pgc => new ProductGraphicsCard()

you are trying to project into a entity class. I can't tell why, but it is not supported by Entity Framework (hence NotSupportedException).

One way to solve the issue is to project into anonymous type:

var query = db.ProductGraphicsCards
    .Where(pgc => pgc.GraphicsCardSKU.StartsWith(term))
    .Select(pgc => new
    {
        GraphicsCardSKU = pgc.GraphicsCardSKU,
        GraphicsCardMemory = pgc.GraphicsCardMemory
    };

var products = await query.ToListAsync();

// ...
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
0
var query = db.ProductGraphicsCards
    .Where(pgc => pgc.GraphicsCardSKU.StartsWith(term))
    .Select(pgc => new ProductGraphicsCard()
    {
        GraphicsCardSKU = pgc.GraphicsCardSKU,
        GraphicsCardMemory = pgc.GraphicsCardMemory
    };

I suppose the problem is here. You will not be able to extract result into a mapped entity ProductGraphicsCard . Try to extract into a not mapped DTO or into an anonymous type.

var query = db.ProductGraphicsCards
    .Where(pgc => pgc.GraphicsCardSKU.StartsWith(term))
    .Select(pgc => new {
        pgc.GraphicsCardSKU,
        pgc.GraphicsCardMemory
    };
mihai
  • 2,746
  • 3
  • 35
  • 56