【发布时间】:2020-09-21 00:07:08
【问题描述】:
我遇到了一个奇怪的问题,当我第二次执行下面的代码时出现异常
此方法存在于 DB 上下文中(实体框架核心)
代码:
public IEnumerable<T> ExecuteStoredProcedure<T>(string spname, params object[] ps)
{
string json = string.Empty;
using (var sqlConnection = (SqlConnection)this.Database.GetDbConnection())
{
var command = sqlConnection.CreateCommand();
command.CommandText = spname;
command.CommandType = System.Data.CommandType.StoredProcedure;
for (int i = 0; i < ps.Length; i++)
{
var obj = ps[i];
System.Reflection.PropertyInfo nameprop = obj.GetType().GetProperty("name");
string name = (string)(nameprop.GetValue(obj, null));
System.Reflection.PropertyInfo valprop = obj.GetType().GetProperty("value");
dynamic val = (dynamic)(valprop.GetValue(obj, null));
command.Parameters.Add(new SqlParameter(name, val));
}
this.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
var rawdata = Serialize(result);
json = JsonConvert.SerializeObject(rawdata, Formatting.Indented);
}
}
return JsonConvert.DeserializeObject<IEnumerable<T>>(json);
}
例外
System.InvalidOperationException: 'The ConnectionString property has not been initialized.'
【问题讨论】:
-
你为什么不let EntityFramework do the work?这将比在 json 之间转换来回高效得多,而且更不容易出错
-
非常类似于这个问题:stackoverflow.com/q/10911635/5803406
-
@AndrewWilliamson 因为 EF Core 无法执行与 dbset 无关的存储过程
-
@devNull 实际上是的,我没注意,但我在 EF Core 中添加了一个与 dbset 无关的动态执行存储过程,它是完全动态的
-
@IssaSaman 你知道哪些存储过程在编译时可用,还是动态的?
标签: c# .net entity-framework asp.net-core entity-framework-core