Dapper多选:除非使用" AS&quot ;,否则嵌套类主键不会映射 [英] Dapper multiselect: Nested class primary key doesn't map unless using "AS"

查看:49
本文介绍了Dapper多选:除非使用" AS&quot ;,否则嵌套类主键不会映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两节课:

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

这样,结果将是Foo和Bar上的所有属性都将映射为Bar.BarId除外.在检查了列名并针对我的Bar类输入数据库后,我仍然找不到任何区别.

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实际上按预期映射,我是否误解了如何使用Dapper或这是一个错误?

Bar.BarId actually mapped as expected, have I misunderstood how to use Dapper or is this a bug?

推荐答案

它正在尝试对 FooId 进行拆分,因此每次看到 FooId 时,它都在切割数据.此用例基本上用于(并非罕见)场景,在该场景中所有表都具有可预测的键,例如 Id .就您而言,这不是您想要的,就像您从数据库中获得的一样:

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 ^^

但是,这在 FooId 上的拆分方式为:

However, that splits on FooId as:

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

这就是为什么 BarId 不包含在第二个对象中的原因,也是为什么将其添加到末尾使其可以工作的原因.

which is why BarId doesn't get included in the second object, and also why adding it to the end makes it work.

还有另一种用法,即IIRC,它接受排序的键进行分割;您将使用:

There is another usage, IIRC, that accepts the sequenced keys to split on; you would use:

splitOn: "FooId,BarId"

这篇关于Dapper多选:除非使用&quot; AS&quot ;,否则嵌套类主键不会映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆