LINQ to Entities查询中是否无法构造实体或复杂类型?

时间:2016-05-14 08:47:59

标签: c# entity-framework linq

这是我的代码,我希望有人可以启发我:

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

给了我一个错误,我无法理解为什么

2 个答案:

答案 0 :(得分:1)

下面

.Select(pgc => new ProductGraphicsCard()

您正在尝试投影到实体类中。我无法说明原因,但实体框架不支持它(因此NotSupportedException)。

解决问题的一种方法是投射到匿名类型:

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

var products = await query.ToListAsync();

// ...

答案 1 :(得分:1)

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

我想问题就在这里。您将无法将结果提取到映射的实体ProductGraphicsCard中。尝试提取到未映射的DTO或匿名类型。

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