使用 Dapper 填充类对象

public class Expenses

{

    public Category Category { get; set; }

    public PaymentModes PaymentModes { get; set; }

}


public class Category

{

    public int CategoryID { get; set; }

    public string CategoryName { get; set; }

}


public class PaymentModes

{

    public int PaymentModeID { get; set; }

    public string PaymentMode { get; set; }

}


public class ViewModel

{

   public IEnumerable<Month> Month { get; set; }

   public IEnumerable<Category> Category { get; set; }

   public IEnumerable<Expenses> Expenses { get; set; }

}

所以我有这些课程。现在我想使用 Dapper 填充 Expense 类对象。但我总是将 Category 和 PaymentModes 设为 null。这是我从 DB 得到的结果:

http://img.mukewang.com/61da9e1a0001543e09100146.jpg

以下是获取费用数据的方法:


public ViewModel FetchSummaryData(Expenses expenses)

{

    DynamicParameters param = new DynamicParameters();

    ViewModel viewModel = new ViewModel();

    param.Add("@flag", expenses.flag);

    var result = db.QueryMultiple("sp_Summary", param, commandType: CommandType.StoredProcedure);

    if (result != null)

    {

        viewModel.Category = result.Read<Category>();

        viewModel.Expenses = result.Read<Expenses>();

    }


    return viewModel;

}

http://img.mukewang.com/61da9e290001427c06730273.jpg

如您所见,该特定 ExpenseID 的 Category 和 PaymentModes 始终为空。如何使用 Dapper 填充这些对象的属性?谢谢你。


临摹微笑
浏览 207回答 1
1回答

慕沐林林

我想您有一个 Expenses 表,其与 PaymentModes 和 Category 表的关系为 1:1。在这种情况下,您的 sp 应该返回 Expenses 表中的所有记录,其中首先列出 Expenses 字段,然后是 PaymentModes 字段,最后是 Category 字段。像这样的东西select e.*, p.PaymentModeId, p.PaymentMode, c.CategoryID, c.CategoryNamefrom tbl_Expenses e inner join PaymentModes p on e.PaymentModeID = p.PaymentModeID&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;inner join Category c on e.CategoryID = c.CategoryIDwhere ......如果您与 PaymentModes 和 Category 表没有关系,但所有内容都存储在单个 Expenses 表中,那么您不需要联接,只需按正确顺序列出所有字段,以便 Dapper 知道如何使用您的字段填充所需的对象select ExpenseID, Price, ExpenseDate, .....,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;PaymentModeID, PaymentMode,&nbsp; &nbsp; &nbsp; &nbsp;CategoryID, CategoryNamefrom tbl_Expenseswhere ....在任何情况下,您都可以使用var result = db.Query<Expenses, PaymentModes, Category, Expenses>("sp_Summary",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(e,p,c) =>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.PaymentModes = p;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.Category = c;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return e;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}, splitOn: "PaymentModeID,CategoryID", param: param, commandType: CommandType.StoredProcedure);此时,结果变量是IEnumerable<Expense>具有正确PaymentModes和Category集的 a。该splitOn参数允许小巧玲珑知道哪个领域应该由调用查询方法所需的三个对象分开你的结果数据。因此,直到 PaymentModeID 的所有字段都分配给 Expenses 变量,然后直到 CategoryID 的字段转到 PaymentModes 变量,而 Category 变量的最后一个字段传递给 lambda 表达式。在 lambda 中,您只需将p和c变量分配给Expenses 变量的适当字段并满足返回 Expenses 变量的 Func 签名
打开App,查看更多内容
随时随地看视频慕课网APP