Dapper 多重选择:嵌套类主键不会映射,除非使用“AS”

发布于 2024-11-24 05:47:07 字数 739 浏览 0 评论 0原文

我有两个类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

◇流星雨 2024-12-01 05:47:07

它尝试对 FooId 进行拆分,因此每次看到 FooId 时都会剪切数据。此用例本质上适用于所有表都有可预测键(例如Id)的场景(并不罕见)。在您的情况下,这不是您想要的,因为您从数据库中获得:

FooId, a, b, c | BarId, FooId, x, y, z
^^ from Foo ^^ | ^^ from Bar ^^

但是,它在 FooId 上拆分为:

FooId, a, b, c, BarId | FooId, x, y, z

这就是为什么 BarId 不包含在第二个对象,以及为什么将其添加到末尾才能使其工作。

还有另一种用法 IIRC,它接受要分割的顺序键;你会使用:

splitOn: "FooId,BarId"

It is trying to do a split on FooId, so every time it sees FooId 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 as Id. In your case, this is not what you want, as you get from the database:

FooId, a, b, c | BarId, FooId, x, y, z
^^ from Foo ^^ | ^^ from Bar ^^

However, that splits on FooId as:

FooId, a, b, c, BarId | FooId, x, y, z

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:

splitOn: "FooId,BarId"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文