C# 在实体框架中使用存储过程(代码优先)

C# 在实体框架中使用存储过程(代码优先),c#,.net,linq,entity-framework,stored-procedures,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<E

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

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代码中获取订单数据?请记住,我只想执行这个存储过程一次。

看一下,其中谈到通过DbContext对象执行存储过程

我想也许你的问题是,你没有把订单作为你查询的一部分拿回来?这是正确的吗?如果是这样,这是因为您只选择客户。您需要创建一个与您期望从查询ie返回的具有customer和order属性的相同模式的对象,或者选择一个动态类型eww

尽管如此,我还是强烈建议在linq中执行此操作:

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

这是一个更好的方法,因为您正在使用EF进行设计,而不是查询不符合您的模型的内容,这是一个很好且完整的答案。但是现在,我如何从我的存储过程中使用linq选择动态类型。我不是100%确定,但类似于var customers=context.Database.SqlQuerySP@Country,categoryParam.ToList;可能是对的我会试试你的解决方案