Dapper MultiMap不适用于NULL值的splitOn [英] Dapper MultiMap doesn't work with splitOn with NULL value
问题描述
我在dapper中遇到MultiMaps问题,试图在包含 NULL
的列上拆分。 Dapper似乎不实例化对象,并且我的映射函数收到 null
而不是对象。
I have a problem with MultiMaps in dapper trying to split on column that contains NULL
. Dapper seems not to instantiate object and my mapping function receives null
instead of object.
这是我的新测试: / p>
Here's my new test:
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();
,因为传递给映射函数的 cat
为 null
。
The line that fails is product.Category.IsNotNull();
due to the fact that cat
passed to mapping function is null
.
我还将此方法添加到了断言类:
I've also added this method to Assert class:
public static void IsNotNull(this object obj)
{
if (obj == null)
{
throw new ApplicationException("Expected not null");
}
}
推荐答案
此是按设计,尽管我可以重新考虑。
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;})
问题是,如果我们允许空白创建 Driver
对象,则每个 Car
将具有 Driver
,即使连接失败。
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.
要解决此问题,我们可以扫描被拆分的整个段,并在映射<$之前确保所有值均为 NULL
c $ c> NULL 对象。这对多重映射器的性能影响很小。
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();
这篇关于Dapper MultiMap不适用于NULL值的splitOn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!