How Dapper chooses between 2 columns with the same name

后端 未结 1 1734
耶瑟儿~
耶瑟儿~ 2021-01-19 10:32

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).

相关标签:
1条回答
  • 2021-01-19 11:08

    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.

    0 讨论(0)
提交回复
热议问题