Dapper查询错误地映射了实体ID [英] Dapper Query incorrectly maps the entity ID

查看:253
本文介绍了Dapper查询错误地映射了实体ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个实体类:

public class PostTag
{
    public int Id { get; set; }
    public string Alias { get; set; }
    public string Name { get; set; }
    public int Level { get; set; }
}

public class PostTagIndex
{
    public int Id { get; set; }
    public int PostTagId { get; set; }
}

我想提请注意一个事实,即他们两个都有一个名为"Id"的字段.

I want to draw attention to the fact that both of them have the same field named 'Id'.

接下来,我以这种方式使用Query(...)方法:

Next, I use Query(...) method this way:

List<PostTag> postTags
    = cn.Query<PostTag>(postTagsSql, new { postId }).AsList();

这是生成的SQL:

exec sp_executesql N'
            SELECT *
            FROM [PostTags] AS pt
            JOIN [PostTagIndexes] AS pti
            ON pt.[Id] = pti.[PostTagId]
            WHERE ([PostId] = @postId)',N'@postId int',@postId=3035

这是它的结果:

Id      Alias   Name    Level   Id      PostId  PostTagId
1014    name1   Name1   0       2020    3035    1014
2014    name2   Name2   1       3021    3035    2014

因此,由于加入并选择了所有列,结果具有两个"Id"列.

So, the result has two 'Id' columns because of joining and selecting all the columns.

我希望在PostTag.Id中放入第一列"Id"值.这不合逻辑吗?但实际上,它将第二个"Id"列作为PostTag的ID.当然,我可以写SELECT pt.*而不是仅仅写SELECT *,但是无论如何,为什么它不采用第一个适当的列名而不是跳过它呢?

I expect to have the first column 'Id' values put in the PostTag.Id. Isn't it logical? But in fact, it takes the second 'Id' column as PostTags' ids. Of course, I can write SELECT pt.* instead of just SELECT *, but anyway why doesn't it take the very first appropriate column name instead of skipping it?

推荐答案

我不认为第一个ID被跳过.我怀疑它已经被秒覆盖了.

I do not think that the first ID is being skipped. I suspect it is being over-written by second.

因此,Dapper映射器模块开始映射.它找到第一个ID列.它正确地映射它.然后,它还会映射其他列.然后,它再次找到ID列并再次正确对其进行映射.

So, Dapper mapper module starts the mapping. It find first ID column. It maps it correctly. Then it also maps other columns. Then it again finds the ID column and maps it correctly again.

正如我上面所说,这就是我所怀疑的.您可能需要看一下Dapper的源代码来确定.

As I said above, this is what I suspect. You may want to have a look at Dapper source code to make sure.

正如您在问题中所说,SELECT pt.*是一种解决方案.其他可能是对pti.ID AS PTI_ID或其他内容使用不同的别名.

As you said in your question, SELECT pt.* is one solution. Other may be to use different alias for pti.ID AS PTI_ID or something.

在映射时还考虑数据类型.但这是我无法改变的东西.

Data type is also considered while mapping. But this is something you cannot change I guess.

这篇帖子讨论了当重复列之一为null时如何映射重复列.

This post discusses about mapping duplicate columns when one of them is null.

这篇关于Dapper查询错误地映射了实体ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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