由于for json path,我有返回json的存储过程。
你如何使用entity-framework-core消费它们?
以下不起作用:
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.
但我们应该如何用entity-framework-core做到这一点?
答案 0 :(得分:0)
在google上搜索了一段时间之后我才明白不支持。如果您在上下文中没有模型,则无法使用entityframework检索数据,请指向:https://docs.microsoft.com/en-us/ef/core/querying/raw-sql和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>>();
我怀疑是否明确关闭连接是否更好。