EF 6 Net Core:我從包含 55 個不同型別欄位的模型(客戶類)創建了一個表,但是當我查詢相關表時,我只需要其中的幾個欄位,所以我最終得到了一個可列舉串列,我需要轉換回客戶模型(出于其他原因)
我只知道如何使用 foreach 回圈來做到這一點,但它有很多代碼。
我嘗試使用下面的這些示例進行轉換,但演員表給出了一個例外,并且 OfType 始終回傳計數 = 0;
所以我使用for回圈的解決方案,但有時要寫很多代碼,因為有些表需要比其他表更多的欄位。是否可以投射?
// This is the (var) result from the query. It has a count of 758
var result = (from r in _context.Customers
select new
{
r.IdNo,
r.Status,
r.RenterName,
}).ToList();
// This always return count = 0
List<Customer> list1 = result.OfType<Customer>().ToList();
// This crash with exception message "Unable to cast object of type...."
List<Customer> list1 = result.Cast<Customer>().ToList();
// That is my possible solution
foreach (var item in result)
{
list1.Add(new Customer() {
// Add all required fields here
........
}))
}
uj5u.com熱心網友回復:
直接創建一個Customer僅包含您需要的值的串列。
var result = context.Customers
.Select(c => new Customer
{
c.IdNo,
c.Status,
c.RenterName,
})
.ToList();
在這種情況下,不需要您的變數list1。你直接擁有你想要的result。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359180.html
上一篇:將`SELECTTOP(1)WITHTIES`轉換為EFCore
下一篇:物體框架,LINQ查詢
