给出以下POCO代码第一实体
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,您可以像下面一样使用Include属性来填写订单
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();
我如何使用上面的命令填充co.Orders中的Orders,似乎我无法在SqlQuery中使用Include语句。这是一个非常简化的示例,仅用于说明目的,实际查询将涉及更多。
这是完全不可能的。直接SQL执行不提供导航属性的填充,您实际上不能使用Include。您必须执行两个单独的SQL查询才能获得Cutomer
和她的Orders
。
我已经使用以下类结构作为解决方法:
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<Order>(
"select cu.CustomerId, ord.OrderId from Orders ord join Customer cu on cu.CustomerId=ord.CustomerId")
.ToList();
对我有用的是在使用结束之前访问相关成员。
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);
}