c# - 使用 Entity Framework 从存储过程中检索表数据

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

我正在使用 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; }
}

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

List<CountryName> countryList = null;

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

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

最佳答案

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

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

    使用这种方法可以防止返回存储过程的 -1。请查看this发布有关 Entity Framework 存储过程问题的更多详细信息。

关于c# - 使用 Entity Framework 从存储过程中检索表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32754315/

相关文章:

c# - 以 "."为前缀的类型名称的 Type.GetType 搜索规则是什么?

c# - 如何处理 Linq2Sql 列表中的空值

sql - 我可以为SQL语句中的常用字符串创建 'reserved word'吗?

c# - 与 Entity Framework 的多个一对多关系

c# - 如何在 UserControl 中创建部分客户区?

c# - 使用 XmlWriter 以迭代方式构建 XML 文件

sql-server - 在列上创建唯一约束会自动创建索引吗?

c# - 单个数据库中每个租户从 1 开始自动递增 ID

asp.net-mvc - 在 mvc 中启用自动迁移

c# - 构建表达式以过滤数据 EF Core