How Dapper chooses between 2 columns with the same

2019-02-25 07:06发布

问题:

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

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?

回答1:

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

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



标签: dapper