简体   繁体   English

Dapper映射抛出无效的转换

[英]Dapper mapping throws invalid cast

Two tables: 两张桌子:

+-Person-+       +--Rank--+
| Id     |       | Id     |
| FName  |       | Name   |
| LName  |       +--------+
| Rank   |
+--------+

The object model looks the exact same except Rank in Person is of type RankModel instead of int. 该对象模型看起来完全相同,除了Person in Rank的类型为RankModel而不是int。

I do a simple inner join on them: 我对它们进行简单的内部联接:

string sql = "SELECT pe.Id, pe.LName, pe.FName, pe.Rank, ra.Id, ra.Name" +
             "FROM Person pe INNER JOIN Rank ra ON ra.Id = pe.Rank";

Then I use Dapper to map: 然后,我使用Dapper进行映射:

return connection.Query<PersonModel, RankModel, PersonModel>(sql, (per, rank) =>
    {
    per.Rank = rank;
    return per;
    }).ToList();

But I get an exception: 但我有一个例外:

InvalidCastException: Invalid cast from 'System.Int16' to 'MainDB.Models.RankModel'.

Clearly it's trying to cast an int to a RankModel, but I can't figure out why -- it should be splitting the return into two objects and then attaching the RankModel object into the Rank property of the PersonModel object. 显然,它试图将int转换为RankModel,但我不知道为什么-应该将返回值分成两个对象,然后将RankModel对象附加到PersonModel对象的Rank属性中。 This is driving me crazy, I've spent 3 hours on this and can't figure out what's going on. 这让我发疯,我已经花了3个小时来弄清楚发生了什么。

You need to add 'splitOn' param in query statement in order to split them into Person, Rank model objects. 您需要在查询语句中添加'splitOn'参数,以便将其拆分为Person,Rank模型对象。

Also your sql needs to be refactored as below 另外您的sql需要如下重构

string sql = "SELECT pe.Id, pe.LName, pe.FName, ra.Id, ra.Name" +
             "FROM Person pe INNER JOIN Rank ra ON ra.Id = pe.Rank";

And your statement should be 你的陈述应该是

return connection.Query<PersonModel, RankModel, PersonModel>(sql, (per, rank) =>
    {
    per.Rank = rank;
    return per;
    }, splitOn:"Id,Id").ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM