【发布时间】: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
通过 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]一样简单