Execute stored procedure and return List in Entity Framework Core

asp.net-core c# entity-framework-core

Question

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?

1
0
12/20/2019 5:57:02 PM

Popular Answer

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 i.e. this.

3
12/20/2019 5:57:37 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow