使用 entityframework 核心检索 json

retrieve json with entityframework core(使用 entityframework 核心检索 json)
本文介绍了使用 entityframework 核心检索 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 用于 json 路径.

你如何使用 entity-framework-core 来使用它们?

How do you consume them with entity-framework-core?

以下不起作用:

var foo = _db.Set<JObject>()
             .FromSql("dbo.Mine @customerid = {0}", _user.guid)
             .FirstOrDefault();

因为 JObject 类型不是模型的一部分:

Because JObject type is not part of the model:

InvalidOperationException: Cannot create a DbSet for 'JObject' because this type is not included in the model for the context.

但是我们应该如何使用 entity-framework-core 来做到这一点?

But how are we supposed to do that with entity-framework-core?

推荐答案

在谷歌上搜索了一段时间后,我了解到尚不支持.如果上下文中没有模型,则无法使用 entityframework 检索数据,请指向:https://docs.microsoft.com/en-us/ef/core/querying/raw-sql 和 https://github.com/aspnet/EntityFrameworkCore/issues/1862

After searching on google for a while I understood is not supported yet. If you don't have a model in the context you can't retrieve data with entityframework, point: https://docs.microsoft.com/en-us/ef/core/querying/raw-sql and https://github.com/aspnet/EntityFrameworkCore/issues/1862

我决定用旧的方式来做:

I resolved doing it the old way:

  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>>();

我怀疑明确关闭连接是否更好.

I am in doubt if it's better to explicitly close the connection or not.

这篇关于使用 entityframework 核心检索 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)