【问题标题】:Retrieve table data from stored procedure using entity framework使用实体框架从存储过程中检索表数据
【发布时间】:2015-09-24 05:56:18
【问题描述】:

我正在使用实体框架 v6。我有一个如下所示的存储过程

CREATE PROCEDURE [dbo].[GetCountryList] 
(
    @CustomerName VARCHAR(MAX), 
    @SearchCriteria VARCHAR(MAX)
)
AS
    BEGIN
    SET NOCOUNT ON

        SELECT CountryID, CountryName FROM dbo.Table1 
        WHERE CustomerName = @CustomerName AND CountryName = @SearchCriteria
    END

现在我有一个模型类

public class CountryName
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }
}

所以我想在List<CountryName> 类型中获取SELECT 查询的结果

List<CountryName> countryList = null;

using (DbEntities dbContext = new DbEntities())
{
    countryList = //my code to collect the result
}

好吧,我可以直接在表上运行 LINQ to SQL,但不幸的是我需要从存储过程中获取数据。那么,我该怎么做呢?

【问题讨论】:

    标签: c# sql-server entity-framework stored-procedures entity-framework-6


    【解决方案1】:
    1. 您需要将存储过程作为函数导入。右键单击实体模型的工作区并选择Add -&gt; Function Import
    2. 在“添加函数导入”对话框中,输入您希望在模型中引用您的存储过程的名称,例如 GetCountryListSP,从下拉列表中选择您的过程,然后选择该过程的返回值Entities 并从下拉列表中选择 CountryName
    3. 然后在代码中:

      var result = db.GetCountryListSP();//Send parameters too
      

      使用这种方法可以防止返回存储过程的-1。请查看this 帖子以获取有关实体框架存储过程问题的更多详细信息。

    【讨论】:

      【解决方案2】:

      您可以在不导入的情况下执行此操作。类似的东西:

      var countryList = dbContext.Database.SqlQuery<CountryName>("[GetCountryList]").ToList();
      

      EntityFramework 有时无法识别或导入 SP ))) 所以,这就是我使用这个 sn-p 节省时间的原因。

      【讨论】:

      • 我使用了这个,但有时它不起作用,ef 不会在实时环境中执行存储过程,但是当我在 sql management studio 或本地 Visual Studio 上执行 proc 时,它可以工作ef 中的某种错误?
      • 我现在将代码更改为 @S.Akbari 建议的 db.procedure();以及它的工作到现在,如果发生任何错误,我也会监控它。
      猜你喜欢
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      相关资源
      最近更新 更多