簡體   English   中英

執行存儲過程並返回List<T> 在實體框架核心

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

.NET Core 的新手。 我的目標是從我的數據庫中返回員工列表(作為列表或 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())
            {
            }
       }
    }
}

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))

我收到一個錯誤

沒有給出對應於所需形式參數“選項”的參數

知道我應該通過什么嗎?

這是在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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM