gpt4 book ai didi

dapper - Dapper MultiMap不适用于NULL值的splitOn

转载 作者:行者123 更新时间:2023-12-03 14:05:03 35 4
gpt4 key购买 nike

我在dapper中尝试对包含NULL的列进行拆分时遇到MultiMaps问题。 Dapper似乎不实例化对象,并且我的映射函数接收null而不是对象。

这是我的新测试:

    class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public void TestMultiMapWithSplitWithNullValue()
{
var sql = @"select 1 as id, 'abc' as name, NULL as description, 'def' as name";
var product = connection.Query<Product, Category, Product>(sql, (prod, cat) =>
{
prod.Category = cat;
return prod;
}, splitOn: "description").First();
// assertions
product.Id.IsEqualTo(1);
product.Name.IsEqualTo("abc");
product.Category.IsNotNull();
product.Category.Id.IsEqualTo(0);
product.Category.Name.IsEqualTo("def");
product.Category.Description.IsNull();
}


失败的行是 product.Category.IsNotNull();,这是因为传递给映射函数的 catnull

我还将此方法添加到了Assert类中:

public static void IsNotNull(this object obj)
{
if (obj == null)
{
throw new ApplicationException("Expected not null");
}
}

最佳答案

这是“设计使然”,尽管我可以重新考虑它。

特别是这种行为有助于左连接。以这个为例:

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


麻烦的是,如果我们允许“空白”创建 Driver对象,则每个 Car都会有一个 Driver,即使连接失败了。

要解决此问题,我们可以扫描要分割的整个段,并在映射 NULL对象之前确保所有值均为 NULL。这对多重映射器的性能影响很小。

要解决您的情况,您可以插入代理列:

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();

关于dapper - Dapper MultiMap不适用于NULL值的splitOn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10744728/

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