简体   繁体   中英

Execute stored procedure and return List<T> in Entity Framework Core

New to .NET Core. My goal is to return list of employees from my database (as a list or dbset):

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())
            {
            }
       }
    }
}

in Startup.cs I have included

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

And in appsettings.json I have my connection string

{
   "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": "*"
}

At the code line

 using (var context = new MyDataContext(options))

I get an error

There is no argument given that correspond to the required formal parameter 'options'

Any idea what I should pass?

This is a method defined on a MyDataContext , so you don't need to create a new one.

Try this:

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 is a property of the current object ie this .

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;
}
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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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