2016-05-14 43 views
0

這裏是我的代碼,我希望有人能賜教:實體或複雜類型不能在LINQ to Entities查詢中構造?

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

給我的錯誤,我不明白爲什麼

+0

請填寫完整的錯誤。 –

回答

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

// ... 
+0

非常感謝! –

相關問題