gpt4 book ai didi

c# - 如何在 Dapper 中为多映射支持命名列?

转载 作者:太空狗 更新时间:2023-10-29 18:30:00 24 4
gpt4 key购买 nike

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

如果您不能这样做,可以使用一个可选的 splitOn (string) 参数,它采用逗号分隔的列列表来处理拆分。

关于c# - 如何在 Dapper 中为多映射支持命名列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6056778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com