2012-07-04 111 views
0

你好,LINQ2SQL得到孩子

我拿一個典型的例子,我有一個Customer表和Purchase表,客戶可以有幾個訂單。

我創建了一個DBML文件,我從「服務器資源管理器窗口」既表DBML編輯下降,產生兩個實體:CustomersPurchases

我有一些對象:

public interface IMyCustomer 
{ 
    int Id { get; set; } 
    string Code { get; set; } 
    string Firstname { get; set; } 
    string Lastname { get; set; } 
    List<IMyPurchase> Purchases { get; set; } 
} 

public class MyCustomer : IMyCustomer 
{ 
    public int Id { get; set; } 
    public string Code { get; set; } 
    public string Firstname { get; set; } 
    public string Lastname { get; set; } 
    public List<IMyPurchase> Orders { get; set; } 
} 

public interface IMyPurchase 
{ 
    int Id { get; set; } 
    string Code { get; set; } 
    DateTime CreationDate { get; set; } 
} 

public class MyPurchase : IMyPurchase 
{ 
    public int Id { get; set; } 
    public string Code { get; set; } 
    public DateTime CreationDate { get; set; } 
} 

var result = 
    from customer in _dataContext.Customers 
    join order in _dataContext.Purchases on customer.Id equals order.IdCustomer 
    select new MyCustomer 
    { 
     Code = customer.Code, 
     Firstname = customer.Firstname, 
     Lastname = customer.Lastname, 
     Id = customer.Id, 
     Purchases = _dataContext.Purchases 
      .Select(x => x.IdCustomer == customer.Id) 
      .Cast<IMyPurchase>() 
      .ToList<IMyPurchase>() 
    }; 

的LINQ查詢工作。對於輸入結果,我有關於customer的所有信息,我有Purchases中的正確行數,但Purchases的每個條目的每個屬性均爲null。我想加載Customer信息和全部purchase

任何想法?

感謝,

回答

0

它不會顯示您有PurchaseMyPurchase之間的轉換邏輯。

此外,Cast<>()方法將嘗試使用隱式轉換,但除非您的Linq-to-SQL實體實現該接口,否則不能以此方式進行轉換。

我的建議是使用像AutoMapper或在您的LINQ語句(類似於你與MyCustomer做什麼)添加轉換邏輯。喜歡的東西:

var result = 
    from customer in _dataContext.Customers 
    join order in _dataContext.Purchases on customer.Id equals order.IdCustomer 
    select new MyCustomer 
    { 
     Code = customer.Code, 
     Firstname = customer.Firstname, 
     Lastname = customer.Lastname, 
     Id = customer.Id, 
     Purchases = _dataContext.Purchases 
      .Where(x => x.IdCustomer == customer.Id) 
      .Select(x => new MyPurchase { 
       Id = x.Id, 
       Code = x.Code, 
       CreationDate = x.CreationDate 
      }).ToList(); 
    }; 
+0

我有很多往返到數據庫中的客戶ID,每次購買我有一個往返,不可能避免這種情況? –

+0

@Johnn Blade使用的連接只會查詢一次。而不是像他的例子那樣選擇一個新的匿名類型,只需使用與我的答案中相同的選擇機制,而不是引用'_dataContext.Purchases'來使用聯合的ObjectSet。 – lukiffer

0

這裏是一個樣本,並在那裏爲在採購

var items = (from p in _dataContext.Purchases 
       join c in _dataContext.Customers 
       on p.CustomerID equals c.ID 
       where (c.ID == customerId) 
       orderby p.CreationDate descending 
       select new { p, c }); 

foreach (var data in items) 
{ 
    // do stuff 
    int customerId = data.c.ID; 
    int purchaseId = data.p.ID; 
    // you can acces all properties of both objects 
} 
+0

當然,我想避免循環 –