2011-10-19 132 views
9

填充子屬性給出以下POCO代碼第一次實體與實體框架類SqlQuery

public class Customer 
{ 
    public int CustomerId { get; set; } 
    public string CustomerTitle { get; set; } 
    public string CustomerFirstName { get; set; } 
    public string CustomerLastName { get; set; } 

    public ICollection<Order> Orders { get; set; } 
} 

public class Order 
{ 
    public int OrderId { get; set; } 
    ... 
    public int CustomerId { get; set; } 

    public Customer Customer { get; set; } 
} 

使用LINQ,你可以得到通過包括物業填寫訂單在

var cust = (from cust in context.Customer 
      where cust.CustomerId == 1 
      select cust) 
      .Include(ord => ord.Orders) 
      .FirstOrDefault(); 

我想以獲得相同的結果使用paramaterised SQL,使用

 Customer co = context.Customer.SqlQuery(
        @"select [Customer].[CustomerId], 
          ... 
          [Order].[OrderId] AS [OrderId], 
          ... 
          from Customer join Order on Customer.CustomerId = Order.CustomerId where Customer.CustomerId = @custid", sqlParm) 
       .FirstOrDefault(); 

我該如何ge t co.Orders中的Orders用上面的命令填充,似乎我不能在Include語句中使用SqlQuery。這只是一個非常簡單的例子,僅供說明之用,實際查詢將更多涉及。

回答

11

這根本不可能。直接SQL執行不提供導航屬性的填充,並且你實際上不能使用包含。您必須執行兩個單獨的SQL查詢才能獲得Cutomer和她的Orders

0

我用下面的類結構,解決方法:

public class Customer 
{ 
    public int CustomerId { get; set; } 
} 

public class Order 
{ 
    public Customer Customer { get; set; } 
    private int _customerId; 
    private int CustomerId { get { return _customerId; } set { Customer.CustomerId = _customerId = value; } } 
    public Order() 
    { 
     Customer = new Customer(); 
    } 
} 

在這種情況下,你不需要運行兩次查詢,下面的查詢將給予以便與客戶:

db.Database.SqlQuery(「從訂單ord加入客戶cu.CustomerId = ord.CustomerId中選擇cu.CustomerId,ord.OrderId」)ToList();

0

對我來說有效的是在使用關閉之前訪問相關成員。

public static Customer GetCustomer (int custid) 
{ 
Customer co = null; 

using (var context = new YourEntities()) 
{ 
    // your code 
    co = context.Customer.SqlQuery(
    @"select [Customer].[CustomerId], 
    ... 
    [Order].[OrderId] AS [OrderId], 
    ... 
    from Customer join Order on Customer.CustomerId = Order.CustomerId where Customer.CustomerId = @custid", sqlParm) 
    .FirstOrDefault(); 


    // my addition 
    // cause lazy loading of Orders before closing the using 
    ICollection<Order> orders = co.Orders; 

    } 

    // can access co.Orders after return. 
    return (co); 
} 
+0

FirstOrDefault()導致查詢被執行,所以這實際上等於執行兩個查詢 –