繁体   English   中英

使用实体框架从存储过程中检索表数据

[英]Retrieve table data from stored procedure using entity framework

我正在使用Entity Framework 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,但不幸的是我要求从存储过程中获取数据。 那么,我该怎么做呢?

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

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

    使用此方法可以防止返回存储过程的-1 有关Entity Framework存储过程问题的更多详细信息,请查看帖子。

你可以在不导入的情况下完成。 像这样的东西:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM