Mapping entity in Dapper

后端 未结 4 959
无人及你
无人及你 2021-01-01 23:39

I\'ve just started working with Dapper and I don\'t seem to find something very simple like mapping an entity to a table in my database:

I have a stored procedure:

相关标签:
4条回答
  • 2021-01-02 00:03

    You could try something like this:

    public class User
    {
        public int Id { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }
    
        #region Remappings
    
        public int UserId
        {
            get { return Id; }
            set { Id = value; }
        }
    
        #endregion
    }
    

    It might be overkill for your example, but I've found it useful in some situations to avoid cluttering every Query<> call with the remapping code.

    0 讨论(0)
  • 2021-01-02 00:07

    It can't, your user class must be defined to match the result coming back from the query.

    Once you've got the result back you must map it manually to another class (or use AutoMapper)

    0 讨论(0)
  • 2021-01-02 00:09

    I would recommend NReco to you. It is performant like dapper but with easy mapping with attributes. nreco

    0 讨论(0)
  • 2021-01-02 00:22

    Dapper deliberately doesn't have a mapping layer; it is the absolute minimum that can work, and frankly covers the majority of real scenarios in the process. However, if I understand correctly that you don't want to alias in the TSQL, and don't want any pass-thru properties - then use the non-generic Query API:

    User user = connection.Query("...", ...).Select(obj => new User {
               Id = (int) obj.UserId,
               FirstName = (string) obj.FirstName,
               LastName = (string) obj.LastName,
               Email = (string) obj.EmailAddress
            }).FirstOrDefault();
    

    or perhaps more simply in the case of a single record:

    var obj = connection.Query("...", ...).FirstOrDefault();
    User user = new User {
          Id = (int) obj.UserId,
          FirstName = (string) obj.FirstName,
          LastName = (string) obj.LastName,
          Email = (string) obj.EmailAddress
    };
    

    The trick here is that the non-generic Query(...) API uses dynamic, offering up members per column name.

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