我有返回 json 的存储过程,感谢对于 json 路径.
您如何通过实体框架核心使用它们?
以下不起作用:
var foo = _db.Set<JObject>()
.FromSql("dbo.Mine @customerid = {0}", _user.guid)
.FirstOrDefault();
因为 JObject 类型不是模型的一部分:
InvalidOperationException: Cannot create a DbSet for 'JObject' because this type is not included in the model for the context.
但是我们应该如何使用实体框架核心来做到这一点呢?
在谷歌上搜索了一段时间后,我明白还不支持。如果您在上下文中没有模型,则无法使用实体框架检索数据,请点:https://learn.microsoft.com/en-us/ef/core/querying/raw-sql and https://github.com/aspnet/EntityFrameworkCore/issues/1862
我决定用老方法来做:
var jsonResult = new System.Text.StringBuilder();
/*"using" would be bad, we should leave the connection open*/
var connection = _db.Database.GetDbConnection() as SqlConnection;
{
await connection.OpenAsync();
using (SqlCommand cmd = new SqlCommand(
"Mine",
connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@customerid", SqlDbType.NVarChar).Value = _user.guid;
using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
{
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
}
}
}
var raw = JArray.Parse(jsonResult.ToString());
var ret = raw.ToObject<List<SiteData>>();
我怀疑是否最好显式关闭连接。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)