viv*_*una 4 c# entity-framework entity-framework-core asp.net-core ef-core-2.0
我通过以下方式在EF Core 2.0中调用存储过程.
private async Task<IEnumerable<TEntity>> InvokeStoredProcedureAsync(string entityName)
{
var storedProcedureName = string.Format(CultureInfo.InvariantCulture, "sp_{0}BulkSelect", entityName);
dynamic temp;
using (MyDbContext MyDbContext = new MyDbContext(_options))
{
MyDbContext.Database.OpenConnection();
DbCommand cmd = MyDbContext.Database.GetDbConnection().CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcedureName;
using (var reader = cmd.ExecuteReader())
{
temp = reader.Cast<Task<IEnumerable<TEntity>>>();
}
}
return await temp;
}
Run Code Online (Sandbox Code Playgroud)
我需要转换DbDataReader为Task<IEnumerable<TEntity>>.
但是在尝试扩展temp变量以查看其值时,我收到此错误.
读取器关闭时无效尝试调用FieldCount.
请参阅随附的屏幕截图.
除了明显的异步代码问题,您无法DbDataReader通过简单调用实现类Cast.如果可能的话,就不需要像Dapper和类似的微型ORM.
EF Core目前没有公开这样做的公开方式.但如果TEntity是模型实体类,您可以简单地使用该FromSql方法:
private async Task<IEnumerable<TEntity>> InvokeStoredProcedureAsync(string entityName)
{
var storedProcedureName = string.Format(CultureInfo.InvariantCulture, "sp_{0}BulkSelect", entityName);
using (var db = new MyDbContext(_options))
{
var result = await db.Set<TEntity>().FromSql(storedProcedureName).ToListAsync();
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
确保SP按TEntity映射返回所有预期的列.
| 归档时间: |
|
| 查看次数: |
1020 次 |
| 最近记录: |