客戶表
每次我運行這個我都會得到一個錯誤:
無法將“System.Collections.Generic.List1[<>f__AnonymousType1 2[System.String,System.String]]”型別的物件轉換為“System.Collections.Generic.IEnumerable1[CRUD__MVC.Models.Customer]”
代碼:
public ActionResult FirstLastName()
{
return View(Name());
}
IEnumerable<Customer>Name()
{
using (AdventureWorksLTDataContext db = new AdventureWorksLTDataContext())
{
return (IEnumerable<Customer>)db.Customers.Select(c => new { FirstName = c.FirstName, LastName = c.LastName }).ToList();
}
}
uj5u.com熱心網友回復:
您可以創建一個新Model類,該類將包含您從Customer該類中選擇的資料:
public class GetCustomerInformation
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
然后你可以Select像這樣要求:
IEnumerable<GetCustomerInformation>Name()
{
using (AdventureWorksLTDataContext db = new AdventureWorksLTDataContext())
{
return (IEnumerable<GetCustomerInformation>)db.Customers.Select(c => new GetCustomerInformation { FirstName = c.FirstName, LastName = c.LastName });
}
}
我在這里做了一個示例供您參考。我手動將資料添加到串列中,然后選擇所需的內容:https ://dotnetfiddle.net/CW9APV
現在,由于您正在查詢資料庫以獲取資料,因此您無法創建物體作為查詢的一部分。物體可以在查詢之外創建并使用DataContext. 然后,您可以使用查詢檢索它們。
所以解決方法是:
生成一個派生自 LINQ to SQL 類的類:
internal class CustomerView: Customer { }
以這種方式撰寫您的查詢:
IEnumerable<Customer> Name()
{
using (AdventureWorksLTDataContext db = new AdventureWorksLTDataContext())
{
var query= db.Customers.Select(c => new CustomerView { FirstName = c.FirstName, LastName = c.LastName }).ToList();
//Cast it back to Customer
return (query.Cast<Customer>())
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416944.html
標籤:
下一篇:LINQ查詢不在
