2017-04-13 161 views
0

我們正在爲我們的體系結構使用EF .NET核心並希望進行基本查詢。因此,我們之後使用的LINQ & EF與延遲加載關閉來選擇父項,在這種情況下,棒項目和子對象中的一些字段。然後將它們返回到我們的強類型項目中。加載相關實體

就是這樣。

var qry = _context.Set<stock>() 
     .Include(p => p.stockitem) 
     .Where(q => q.customer == accountNo) 
     .Select(r => new stock() { 
      customer = r.customer, 
      r.stockitem.select(s => new {id, s.id, s.name }}) 
     .ToList(); 

那麼有可能這樣做嗎?基本上可以從我們的子對象中得到幾個列。然後讓所有的東西在強類型對象中返回。

+0

行r.stockitem.select(s => new {id,s.id,s.name}})不是很正確,它不會在初始化程序塊中設置屬性......括號也不正確... –

回答

0

首先創建將選擇的數據將被存儲在模型(該模型只是一個例子):

public class MyNewCustomer 
{ 
    public string CustomerAccount { get; set; } 
    public Dictionary<int, string> Items { get; set; } 
} 

在此之後,你可以從你的選擇創建一個新的對象:

var data = _context.Stocks 
    .Include(p => p.stockitem) 
    .Where(p => p.customer == accountNo) 
    .Select(p => new MyNewCustomer 
    { 
     CustomerAccount = p.customer, 
     Items = p.stockitem.ToDictionary(s => s.id, s => s.name) 
    }).ToList(); 

PS:我用Dictionary,因爲你沒有提供實際的模型。你可以選擇任何種類的List<TObject>你想要的。