在Entity Framework中使用存储过程(代码优先)

Mah*_*kar 5 .net c# linq stored-procedures entity-framework

我使用此代码来定义我的存储过程

CREATE PROCEDURE [dbo].[SP]
(@Country NVARCHAR(20))
AS
BEGIN
    SET NOCOUNT ON;
    SELECT c.*,O.* from Customers
           as c inner join orders O on c.CustomerID=o.CustomerID

     where  c.Country=@Country 
END
Run Code Online (Sandbox Code Playgroud)

这是我的C#代码:

IList<Entities.Customer> Customers;

using (var context = new NorthwindContext())
{
   SqlParameter categoryParam = new SqlParameter("@Country", "London");
   Customers = context.Database.SqlQuery<Entities.Customer>("SP @Country",  categoryParam).ToList();
}
Run Code Online (Sandbox Code Playgroud)

问题在这里:

我想从Orders表中发送数据,我的存储过程生成这个给我.如何Orders在C#代码中获取数据?记住我只想执行一次这个存储过程.

Not*_*ple 7

看看Entity Framework Code First是否支持存储过程?http://blogs.msdn.com/b/wriju/archive/2011/05/14/code-first-4-1-using-stored-procedure-to-insert-data.aspx谈论执行存储通过DbContext对象进行proc.

我想也许你的问题是你没有收到订单作为查询的一部分?它是否正确?如果是这样,那是因为您只选择客户.您需要创建一个与您希望从查询返回的相同模式的对象(即具有客户和订单属性)或选择动态类型(eww).

话虽如此,我强烈建议在linq中这样做:

from c in context.Customers.Include(c=>c.Orders)
where c.Country == country
select c;
Run Code Online (Sandbox Code Playgroud)

这是一种更好的方法,因为您使用EF来实现它的设计而不是查询不适合您模型的东西