Dapper 多重选择:嵌套类主键不会映射,除非使用“AS”
我有两个类:
class Foo{
public int FooId { get; set; }
...
public Bar Bar { get; set }
}
class Bar{
public int BarId { get; set; }
public int FooId { get; set }
...
}
当我像这样运行查询时:
sqlConnection.Query<Foo, Bar, Foo>(
"SELECT * FROM Foo JOIN Bar ON Foo.FooId = Bar.FooId",
(foo, bar) => {
foo.Bar = bar;
return foo;
},
splitOn: "FooId");
结果将是 Foo 和 Bar 上的所有属性都将映射,除了 Bar.BarId 之外。 在根据我的 Bar 类检查数据库中的列名称和类型后,我仍然找不到任何差异。
我偶然发现的一件奇怪的事情是,如果我写:
"SELECT *, BarId AS BarId FROM Foo JOIN Bar ON Foo.FooId = Bar.FooId"
Bar.BarId 实际上按预期映射,我是否误解了如何使用 Dapper 或者这是一个错误?
I have two classes:
class Foo{
public int FooId { get; set; }
...
public Bar Bar { get; set }
}
class Bar{
public int BarId { get; set; }
public int FooId { get; set }
...
}
when i then run the query like this:
sqlConnection.Query<Foo, Bar, Foo>(
"SELECT * FROM Foo JOIN Bar ON Foo.FooId = Bar.FooId",
(foo, bar) => {
foo.Bar = bar;
return foo;
},
splitOn: "FooId");
the result would then be that all properties on both Foo and Bar will map up Except for Bar.BarId.
After checking the column name and type in the database against my Bar class I still couldn't find any differences.
One strange thing I stumbled upon was that if I wrote:
"SELECT *, BarId AS BarId FROM Foo JOIN Bar ON Foo.FooId = Bar.FooId"
Bar.BarId actually mapped as expected, have I misunderstood how to use Dapper or is this a bug?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它尝试对
FooId
进行拆分,因此每次看到FooId
时都会剪切数据。此用例本质上适用于所有表都有可预测键(例如Id
)的场景(并不罕见)。在您的情况下,这不是您想要的,因为您从数据库中获得:但是,它在
FooId
上拆分为:这就是为什么
BarId
不包含在第二个对象,以及为什么将其添加到末尾才能使其工作。还有另一种用法 IIRC,它接受要分割的顺序键;你会使用:
It is trying to do a split on
FooId
, so every time it seesFooId
it is cutting the data. This use-case is essentially intended for the (not uncommon) scenario where all the tables have a predictable key such asId
. In your case, this is not what you want, as you get from the database:However, that splits on
FooId
as:which is why
BarId
doesn't get included in the second object, and also why adding it to the end makes it work.There is another usage, IIRC, that accepts the sequenced keys to split on; you would use: