使用存储过程(代码第一)
问题描述:
我用这个代码来定义我的存储过程使用存储过程(代码第一)
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 [email protected]
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
数据?记住我只想执行一次这个存储过程。
答
看看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什么其设计,而不是查询的东西不适合你模型
tnkx为你很好和完整answer.but现在,我怎样才能从我的存储过程中选择linq的动态类型。 – 2012-01-11 06:11:26
即时通讯不是100%肯定,但类似var customers = context.Database.SqlQuery(“SP @Country”,categoryParam).ToList();将可能是正确的 –
2012-01-11 07:14:31
tnkx我会尝试你的解决方案 – 2012-01-11 07:16:27