简体   繁体   English

Dapper中的地图数据库和模型

[英]Map database and Model in Dapper

My database: 我的数据库:

uId | uName | uAge | uAddress

Model: 模型:

public int Id {get; set;}
public int Name {get; set;}
public int Age {get; set;}
public int Address {get; set;}

Query: 查询:

public User GetUserById(int userId)
{
   using (SqlConnection con = new SqlConnection(_connectionString.Value.ConnectionString))
   {
       var param = new DynamicParameters();
       param.Add("@userID", userId);
       return con.Query("GetuserDetails", param, null, true, 0, System.Data.CommandType.StoredProcedure).SingleOrDefault();
   }
}

Is there any way that I can map these? 有什么办法可以映射这些?

On the other side I tried to change my property as per DB and used JsonProperty in the annotation, 另一方面,我尝试根据数据库更改属性,并在注释中使用了JsonProperty

[JsonProperty("Name")]
public string uName { get; set; }

But after consuming the data in the client and converting back to User object will it throws null again. 但是在使用了客户端中的数据并将其转换回User对象之后,它将再次抛出null。 I can't change the column name in the DB as that will be the standard and I wanted the property name to be clean (Name, Age) too. 我不能更改数据库中的列名,因为这将是标准的,我也希望属性名也干净(名称,年龄)。

Any help? 有什么帮助吗? Am I wrong somewhere? 我在某个地方错了吗?

What you have to do is create a constructor with the names of the columns and the correct types. 您要做的是使用列名称和正确的类型创建一个构造函数。 Assuming you are on SQL-Server, it would be the following: 假设您使用的是SQL Server,它将是以下内容:

public class User
{
   public User(int uId, string uName, int uAge, string uAddress)
   {
      Id = uId;
      Name = uName;
      Age = uAge;
      Address = uAddress;
   }
}

Now you can change the sql-query invocation to this: 现在,您可以将sql-query调用更改为:

return con.Query<User>("GetuserDetails", param, null, true, 0, System.Data.CommandType.StoredProcedure).SingleOrDefault();

Now Dapper is able to map them to your class because it finds a constructor matching to the column- names and types. 现在,Dapper能够将它们映射到您的类,因为它找到了与列名和类型匹配的构造函数。 If you need an empty constructor as well, just add one without any parameters. 如果还需要一个空的构造函数,只需添加一个不带任何参数的构造函数即可。

Why don't you use ColumnAttributeTypeMapper ? 为什么不使用ColumnAttributeTypeMapper

[Column("uId")]
public int Id {get; set;}
[Column("uName")]
public int Name {get; set;}
[Column("uAge")]
public int Age {get; set;}
[Column("uAddress")]
public int Address {get; set;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM