Dapper MultiMap doesn't work with splitOn with NULL value

独自空忆成欢 提交于 2019-12-03 05:07:14

This is "by-design" though I would be ok to revisit it.

In particular this behaviour is there to help with left joins. Take this for example:

cnn.Query<Car,Driver>("select * from Cars c left join Drivers on c.Id = CarId",
   (c,d) => {c.Driver = d; return c;}) 

Trouble is that if we allow a "blanket" creation of a Driver object, every Car is going to have a Driver even ones where the join failed.

To work around we could scan the entire segment being split and ensure ALL values are NULL before mapping a NULL object. This will have a very minor perf impact on the multi mapper.

To workaround for your case, you could insert a surrogate column:

var sql = @"select 1 as id, 'abc' as name, '' as split, 
            NULL as description, 'def' as name";
    var product = connection.Query<Product, Category, Product>(sql, (prod, cat) =>
    {
        prod.Category = cat;
        return prod;
    }, splitOn: "split").First();

For all who wants visualization :

Dapper splits by the last equal column name :

Let's swap location of columns :

null problem :

Swapped column null :

Spliton to the rescue :

I have the same issue, i'm forced to select a fake 'split' columns to make Dapper fill my object instead of just null it;

My workaround :

    string req = @"
SELECT
    T1.a as PropA,
    T1.b as PropB,

    1 as Split,
    T2.a as PropA,
    T2.b as PropB,

    1 as Split,
    ...
FROM
    xxx T1,
    yyy T2,
    ...";
    using (var db = new OracleConnection(...))
    {
        return db.Query(
            req,
            (T1, T2) => {
                ...
            },
            splitOn:'Split,Split,...');
    }

Dapper should have an option to avoid the splitOn:'Split,Split,...'

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