如何在Dapper中為多映射支持命名列?

c# dapper

var sql = @"SELECT
    a.id AS `Id`, 
    a.thing AS `Name`, 
    b.id AS `CategoryId`,
    b.something AS `CategoryName`  
FROM ..";

var products = connection.Query<Product, Category, Product>(sql,
    (product, category) =>
    {
        product.Category = category;
        return product;
    }, 
    splitOn: "CategoryId");

foreach(var p in products)
{
    System.Diagnostics.Debug.WriteLine("{0} (#{1}) in {2} (#{3})", p.Name, p.Id, p.Category.Name, p.Category.Id);
}

結果是:

'First (#1) in  (#0)'
'Second (#2) in  (#0)'

CategoryId和CategoryName具有以下值

var products = connection.Query(sql).Select<dynamic, Product>(x => new Product
{
    Id = x.Id,
    Name = x.Name,
    Category = new Category { Id = x.CategoryId, Name = x.CategoryName }
});

結果是:

'First (#1) in My Category (#10)'
'Second (#2) in My Category (#10)'

我正在連接MySQL數據庫,如果它與它有任何關係。

一般承認的答案

最簡單的方法是將它們全部稱為Id (不區分大小寫,所以只需a.idb.id就可以了);然後你可以使用:

    public void TestMultiMapWithSplit()
    {
        var sql = @"select 1 as Id, 'abc' as Name, 2 as Id, 'def' as Name";
        var product = connection.Query<Product, Category, Product>(sql,
           (prod, cat) =>
           {
               prod.Category = cat;
               return prod;
           }).First();
        // assertions
        product.Id.IsEqualTo(1);
        product.Name.IsEqualTo("abc");
        product.Category.Id.IsEqualTo(2);
        product.Category.Name.IsEqualTo("def");
    }

如果您不能這樣做,則有一個可選的splitOnstring )參數,該參數採用以逗號分隔的列列表來處理拆分。



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因