使用存储过程中的实体框架(code第一) [英] Use stored procedure in Entity Framework (code first)

查看:227
本文介绍了使用存储过程中的实体框架(code第一)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个code来定义我的存储过程

I use this code to define my stored procedure

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#code:

and this is my C# code:

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();
}

问题是在这里:

Problem is here :

我想消息订单数据表,我的存储过程产生这样对我。我怎样才能得到我的C#code中的订单的数据?记得我想执行此存储过程只有一次。

I want to message the data from Orders table and my stored procedure generate this to me. How can I get the Orders data in my C# code? Remember I want to execute this stored procedure only once.

推荐答案

看看<一href="http://stackoverflow.com/questions/4845246/does-entity-framework-$c$c-first-support-stored-procedures">Does实体框架code首先支持存储过程?和<一href="http://blogs.msdn.com/b/wriju/archive/2011/05/14/$c$c-first-4-1-using-stored-procedure-to-insert-data.aspx">http://blogs.msdn.com/b/wriju/archive/2011/05/14/$c$c-first-4-1-using-stored-procedure-to-insert-data.aspx其中谈到通过的DbContext对象执行存储过程。

Take a look at Does Entity Framework Code First support stored procedures? and http://blogs.msdn.com/b/wriju/archive/2011/05/14/code-first-4-1-using-stored-procedure-to-insert-data.aspx which talk about executing a stored proc via a DbContext object.

我想也许你的问题是,你没有得到的订单回来作为查询的一部分?它是否正确?如果是这样,这是因为你只选择客户。您需要创建相同的架构的对象像您期望从你的查询返回(即同时具有客户和订单属性),或者选择到动态类型(EWW)。

I think perhaps your issue is that you aren't getting the orders back as part of your query? is this correct? If so this is because you are only selecting customers. You need to either create an object of the same schema as you expect to be returned from your query (ie that has both customer and order properties) or select into a dynamic type (eww).

说到这里我强烈建议在LINQ这样做,而不是:

Having said that i strongly recommend doing this in linq instead:

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

这是一个更好的方法,因为使用的是EF什么其设计并没有查询的东西不适合你的模型

This is a much better approach as you are using EF for what its designed for and not querying for something which doesn't fit your model

这篇关于使用存储过程中的实体框架(code第一)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆