【发布时间】: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