Dapper Query incorrectly maps the entity ID

…衆ロ難τιáo~ 提交于 2020-01-04 14:12:26

问题


I have 2 entity classes:

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; }
}

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

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

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

Here is the generated 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

And here is its result:

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

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

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?


回答1:


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

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.

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

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.

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




回答2:


In this instance you're using Dapper incorrectly I'm afraid. Your SQL is returning 2 entities worth of columns but you're asking Dapper to map to only one of them.

You should either use the multi-mapping query or select just those columns that are needed for the PostTag entity.



来源:https://stackoverflow.com/questions/49601732/dapper-query-incorrectly-maps-the-entity-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!