【问题标题】:Execute stored procedure and return List<T> in Entity Framework Core在 Entity Framework Core 中执行存储过程并返回 List<T>
【发布时间】:2021-04-15 22:10:56
【问题描述】:

.NET Core 的新手。我的目标是从我的数据库中返回员工列表(作为列表或数据库集):

public class MyDataContext : DbContext
{
    public MyDataContext(DbContextOptions<MyDataContext> options)
    : base(options)
    {
    }

    public List<Employee> GetEmployeeList(int EmpId, int DeptId)
    {
       // here I want to call my stored procedure, pass two parameters and execute it
       // At this point I am getting error of null argument 
       using (var context = new MyDataContext(options))
       using (var command = new MYDataContext.Database.GetDbConnection().CreateCommand())
       {
            command.CommandText = "myStoredProcedureName";
            command.CommandType = CommandType.StoredProcedure;
            context.Database.OpenConnection();

            using (var result = command.ExecuteReader())
            {
            }
       }
    }
}

Startup.cs我已经收录了

services.AddDbContext<MyDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

appsettings.json 我有我的连接字符串

{
   "ConnectionStrings": {
       "DefaultConnection": "Server=ser11; Database=myDb; User Id=user; Password=123; Trusted_Connection=False; MultipleActiveResultSets=true"
   },
   "Logging": 
   {
       "LogLevel": 
           {
               "Default": "Information",
               "Microsoft": "Warning",
               "Microsoft.Hosting.Lifetime": "Information"
           }
   },
   "AllowedHosts": "*"
}

在代码行

 using (var context = new MyDataContext(options))

我收到一个错误

没有给出与所需形式参数“选项”相对应的参数

知道我应该通过什么吗?

【问题讨论】:

  • options 在哪里设置在GetEmployeeList,它是全局的吗?我没有看到它们被传递到函数中或在构造函数中设置为属性?
  • 我在 Startup.cs 和 appsettings 中有所有设置。除了上面的 storeprocedure 执行代码之外,它运行良好。
  • 如果你都保存了你就不需要发送任何东西
  • 感谢大卫,chrisbyte using (var context = new MyDataContext(options)) 没有必要,当我删除它时一切正常,感谢您的帮助

标签: c# asp.net-core entity-framework-core


【解决方案1】:

这是在MyDataContext 上定义的方法,因此您无需创建新方法。

试试这个:

public List<Employee> GetEmployeeList(int EmpId, int DeptId)
{
   using (var command = Database.GetDbConnection().CreateCommand())
   {
      command.CommandText = "myStoredProcedureName";
      command.CommandType = CommandType.StoredProcedure;
      Database.OpenConnection();
      using (var result = command.ExecuteReader())
      {

      }
   }
}

Database 是当前对象的属性,即this

【讨论】:

  • 谢谢,现在已修复,但是当我的数据库中有记录并且数据库也处于打开状态时,我的列表返回 null。如何将多个参数传递给我的 s.procedure?以及如何将它们读入对象类?
  • 我正在使用 ADO.NET 样式来读取并映射到我在文档中看不到的对象类
  • 如果您使用 EF Core,则不需要 ADO.NET 样式代码。 EF 通过简单的ToList() 为您完成所有艰苦的工作。如果您必须使用SqlReader,网络上有许多 示例。这是一个stackoverflow.com/a/18909963/8126362
  • @MedhanieW。很高兴为您提供帮助
【解决方案2】:
public List<Employee> GetEmployeeList(int EmpId, int DeptId)
{

List<Employee> result = new List<Employee>();
using (var context = new MyDataContext(options))
using (var command = new MYDataContext.Database.GetDbConnection().CreateCommand())
{
    command.CommandText = "myStoredProcedureName";
    command.CommandType = CommandType.StoredProcedure;
    context.Database.OpenConnection();

    using (var reader = command.ExecuteReader())
    {
        if (reader.NextResult())
        {
            result = new List<Employee>();
            while (reader.Read())
            {
                result.Add(Populators.PopulateEmployee(reader));
            }
        }
    }
}
return result;
}

【讨论】:

    【解决方案3】:
    using Microsoft.EntityFrameworkCore;
    using System.ComponentModel.DataAnnotations.Schema;
    public class Employee
    {
        // Column must match the column name returned by the stored procedure
        [Column("FirstName")]
        public string FirstName { get; set; }
    
        [Column("LastName")]
        public string LastName{ get; set; }
    }
    
    public partial class MyDataContext: DbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
          modelBuilder.Entity<Employee>(entity =>
          {
            entity.HasNoKey();
          });
        }
    }
    
    public async Task<List<Employee>> GetEmployeeList(int EmpId, int DeptId)
    {
       return await Context.Set<Employee>()
                           .FromSqlRaw($"EXECUTE dbo.myStoredProcedureName {EmpId} {DeptId}")
                           .ToListAsync();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      相关资源
      最近更新 更多