Dapper如何在两个具有相同名称的列之间进行选择 [英] How Dapper chooses between 2 columns with the same name

查看:81
本文介绍了Dapper如何在两个具有相同名称的列之间进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些继承的代码,这些代码使用Dapper将SQL SELECT映射到对象中。 SELECT有多个具有相同名称的列(为简便起见,省略了一些列)。

I have some inherited code that uses Dapper to map a SQL SELECT into an object. The SELECT has multiple columns with the same name (some columns are omitted for brevity).

SELECT
    created_timestamp AS CreatedDate,
    imported_timestamp AS CreatedDate
FROM Orders
WHERE OrderId = @OrderId

对数据的分析显示,每个记录仅填充2个CreatedDate列之一。运行一些测试表明,Dapper似乎选择了非NULL的CreatedDate。我找不到有关Dapper如何处理这种情况的任何文档。我可以依靠Dapper始终选择非NULL值吗?

An analysis of the data shows only one of the 2 CreatedDate columns are populated for each record. Running some tests revealed that Dapper seems to be picking the non-NULL CreatedDate. I couldn't find any documentation on how Dapper handles this situation. Can I rely on Dapper always picking the non-NULL value?

推荐答案

Dapper是(micro)ORM,应该用于数据库CRUD操作。

Dapper is (micro) ORM and it should be used for database CRUD operations.

也就是说,您的业务逻辑应该放在其他地方。实现非常简单。不要创建名称重复的列。

That said, your business logic should go somewhere else. Implementation is quite simple. Do not create columns with duplicate names. Get data from database using dapper and apply your business logic at other place like checking null or else.

//Following is query
SELECT
    created_timestamp AS CreatedDate,
    imported_timestamp AS ImportedDate
FROM Orders
WHERE OrderId = @OrderId

//Following is your POCO/DTO
public class Order
{
    public int OrderId;//or Guid if that suits you
    public string CreatedDate;//or DateTime if that suits you
    public string ImportedDate;//or DateTime if that suits you
}

//Following is your business logic
Order order = orderService.GetOrder(orderId);
if(order.CreatedDate != null)
    //Do something
else if(order.ImportedDate != null)
    //Do something else

根据您的研究,即使Dapper选择了非null列;将来的版本可能无法保证。

Based on your research, even if non-null column is chosen by Dapper; this may not be guaranteed in future versions.

这篇关于Dapper如何在两个具有相同名称的列之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆