【问题标题】:Dapper Mapping of Nested Objects within Nested Objects in .NET.NET 中嵌套对象内嵌套对象的简洁映射
【发布时间】:2022-01-04 00:48:48
【问题描述】:

我目前正在处理来自 SQL DB 的一组数据,并且想知道使用 Dapper 映射它的正确方法,关于 JSON 对象中的列。

通过整体查询中的 FOR JSON PATH 选择语句来自数据库的 JSON 对象的形状:

widget: [
 {
  id: 'int',
  name: 'string',
  x: 'int',
  y: 'int'
 },{...}
]

我想将 X 和 Y 值映射到我的 .NET 应用程序中的一个类。 生成如下所示的对象:(其中 X 和 Y 值嵌套在 Layout 对象中)

widget: [
 {
  id: 'int',
  name: 'string',
  layout: {
    x: 'int',
    y: 'int'
  }
 },{...}
]

C# 类如下所示:(此处省略 {get;set;})

public class Data {
  public int Id
  public string Name
  public List<Widget> Widgets
}

public class Widget {
  public int Id
  public string Name
  public WidgetLayout Layout
}

public class WidgetLayout {
  public int X
  public int Y
}

使用 SQLMapper 方法(QueryAsync),我能够有效地将 Widget 映射到 Data 类,但我无法在映射布局到 Widget。

通过 Dapper 进行映射如下所示:

var results = (await conn.QueryAsync<Data, string, Data>(storedProc, (data, widgets) =>
List<Widget> widgetList= JsonConvert.DeserializeObject<List<Widget>>(widgets); -- JSON object
data.Widgets = widgetList;
return data;
}, parameters, splitOn: "Widgets",

我是 Dapper 的新手,想知道是否可以映射反序列化的 json 对象,以便 X 和 Y 值嵌套在整个 Widget 对象中。

对于此问题中未提供的任何信息的缺失,我们深表歉意,因此,如果我需要其他信息,请告诉我。

非常感谢。

【问题讨论】:

  • 您考虑过更改 SQL 吗?就像将列别名更改为AS [layout.x] 一样简单

标签: c# sql .net orm dapper


【解决方案1】:

感谢 Charlieface 的评论,这个问题已经解决了。

更改了 sProc 中的别名,它已正确映射到 .Net 应用程序中的模型。

来自: ,[widgetLayout.X] ,[widgetLayout.Y] ...

到: ,[widgetLayout.X] 作为 [Layout.X] ,[widgetLayout.Y] 作为 [Layout.Y] ...

从数据库到 API 的输出如我所愿,如问题中所述。

谢谢查理脸!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2013-08-01
    • 2017-07-20
    • 2018-03-17
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多