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

时间:2012-01-10 17:27:29

标签: c# .net linq entity-framework stored-procedures

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

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

这是我的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();
}

问题出在这里:

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

1 个答案:

答案 0 :(得分:7)

查看Does Entity Framework Code First support stored procedures?http://blogs.msdn.com/b/wriju/archive/2011/05/14/code-first-4-1-using-stored-procedure-to-insert-data.aspx,其中讨论了通过DbContext对象执行存储过程。

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

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

from c in context.Customers.Include(c=>c.Orders)
where c.Country == country
select c;

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

相关问题