【问题标题】:Dapper mapping columns to entity properties?Dapper 将列映射到实体属性?
【发布时间】:2014-10-30 17:35:38
【问题描述】:

我正在使用 Dapper 的 Query 来搜索多条记录:

public class Product
{
    public int Id {get; set}
    public string Name {get; set}
    public int CategoryId {get; set}
]

public IEnumerable<Product> GetProducts(int categoryId)
{
    var connection = DataContext.Database.Connection;

    var sql = "SELECT * FROM products WHERE category_id = @categoryId";

    var result = connection.Query<Product>(sql, new { categoryId });

    return result;
}

查询本身返回请求的记录,但列表中的每个对象都有空字段。

那么如何将列映射到实体的属性?

我不想在 sql 语句中添加列别名。装饰实体的属性也不是一种选择,因为实体是由 EF 设计器生成的。

【问题讨论】:

  • 您可以使用 DapperExtensions 包并通过从 ClassMapper 或 AutoMapper 继承来为您的类创建自定义映射器。有关更多信息,请参阅this。没有时间给出完整的答案。我相信您也需要从使用 Query 方法更改为使用 Get 方法。

标签: c# sql-server dapper


【解决方案1】:

您的 Product 类必须定义为匹配从查询返回的结果。所以你能做的是——

public IEnumerable<Product> GetProducts(int categoryId)
{
    var connection = DataContext.Database.Connection;

    var sql = "SELECT * FROM products WHERE category_id = @categoryId";

    var result = connection.Query<Product>(sql, new { categoryId }).Select(p => new Product {
           Id = (int)p.ProductId,
           Name = (string)p.ProductName,
           CategoryId  = (int)p.ProductCategoryId
        });

    return result;
}

【讨论】:

  • 这是一个很好的答案,因为对于一次性查询和映射,此解决方案就足够了。但是,对于许多需要映射的查询,DapperExtensions 是要走的路。
  • 是的,对于许多查询或一些复杂的对象,您需要使用 DapperExtensions。无论如何,很高兴帮助你,如果你能支持我的回答,谢谢.. :)
猜你喜欢
  • 2013-04-05
  • 1970-01-01
  • 2012-03-20
  • 1970-01-01
  • 2017-09-20
相关资源
最近更新 更多