简体   繁体   English

将 Dapper 结果映射到嵌套对象

[英]Map dapper result to nested object

I have a dapper query that returns a set of columns from the DB:我有一个小巧的查询,它从数据库返回一组列:

public async Task<WipCommentCalculation> GetExpenditureCommentsAndData(int projectId, string glPeriodName)
        {
            var output = await _db.LoadData<WipCommentCalculation, dynamic>("dbo.Sp_Get_Expenditure_Comments_Values",
                new { projectId, glPeriodName },
                ConnectionStringName,
                true);

            return output.FirstOrDefault()!;
        }

this is my LoadData method:这是我的 LoadData 方法:

public async Task<List<T>> LoadData<T, U>(string sqlStatement, U parameters, string connectionStringName, bool isStoredProcedure = false)
        {
            Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;

            string connectionString = _config.GetConnectionString(connectionStringName)!;

            CommandType commandType = CommandType.Text;

            if (isStoredProcedure == true)
            {
                commandType = CommandType.StoredProcedure;
            }

            using (IDbConnection connection = new SqlConnection(connectionString))
            {
                var rows = await connection.QueryAsync<T>(sqlStatement, parameters, commandType: commandType);
                return rows.ToList();
            }
        }

my WipCommentCalculation class:我的 WipCommentCalculation 类:

public class WipCommentCalculation
    {
        public Calculations Calculations{ get; set; }

        public CommentModel? Comments { get; set; }

        public int ProjectId{ get; init; }

        public string? ProjectNumber { get; init; }

        public string? GlPeriodName { get; init; }

        public DateTime? LastUpdatedDate { get; set; }

        public string? Status { get; set; }
    }

my issue is that the mapping works well for all not nested objects (Status, LastUpdatedDate, etc) but the Calculations and CommentModel are coming as empty.我的问题是映射适用于所有非嵌套对象(Status、LastUpdatedDate 等),但 Calculations 和 CommentModel 为空。

The mapping inside the object is valid, they have the correct names, is there something I'm missing for getting the entire object here?对象内部的映射是有效的,它们具有正确的名称,我在这里获取整个对象是否缺少一些东西?

for example my query returns among other columns:例如,我的查询在其他列中返回:

Palaborcomment, 
Panonlaborcomment, 
Pasubcontractorcomment, 
Pmlaborcomment, 
Pmnonlaborcomment, 
Pmsubcontractorcomment

and my object "CommentModel" has the following definition:我的对象“CommentModel”具有以下定义:

public class CommentModel
{
    [MaxLength (400, ErrorMessage = "Max length for this field is 400 chars")]
    public string? PALaborComment { get; set; }

    [MaxLength(400, ErrorMessage = "Max length for this field is 400 chars")]
    public string? PANonLaborComment { get; set; }

    [MaxLength(400, ErrorMessage = "Max length for this field is 400 chars")]
    public string? PASubContractorComment { get; set; } 

    [MaxLength(400, ErrorMessage = "Max length for this field is 400 chars")]
    public string? PMLaborComment { get; set; }

    [MaxLength(400, ErrorMessage = "Max length for this field is 400 chars")]
    public string? PMNonLaborComment { get; set; }

    [MaxLength(400, ErrorMessage = "Max length for this field is 400 chars")]
    public string? PMSubcontractorComment { get; set; }
}

the SQL storedprocedure basically is this (simplified): SQL存储过程基本上是这样的(简化):

Select Id, 
    Projectid, 
    Projectnumber, 
    Glperiodname, 
    Palaborcomment, 
    Panonlaborcomment, 
    Pasubcontractorcomment, 
    Pmlaborcomment, 
    Pmnonlaborcomment, 
    Pmsubcontractorcomment, 
    Billablelabor, 
    Billablenonlabor, 
    Billablesubcontractor, 
    Unbilledlabor, 
    Unbillednonlabor, 
    Unbilledsubcontractor, 
    Billingholdlabor, 
    Billingholdnonlabor, 
    Billingholdsubcontractor, 
    Last_Updated_Date, 
    Status
 From Table

and a result row:和结果行:

+----+-----------+---------------+--------------+----------------+-------------------+------------------------+----------------+-------------------+------------------------+---------------+------------------+-----------------------+---------------+------------------+-----------------------+------------------+---------------------+--------------------------+-------------------------+--------+
| Id | ProjectId | ProjectNumber | GlPeriodName | PALaborComment | PANonLaborComment | PASubContractorComment | PMLaborComment | PMNonLaborComment | PMSubcontractorComment | BillableLabor | BillableNonLabor | BillableSubcontractor | UnbilledLabor | UnbilledNonLabor | UnbilledSubcontractor | BillingHoldLabor | BillingHoldNonLabor | BillingHoldSubcontractor | Last_Updated_Date       | Status |
+====+===========+===============+==============+================+===================+========================+================+===================+========================+===============+==================+=======================+===============+==================+=======================+==================+=====================+==========================+=========================+========+
| 1  | 1622554   | F5Y67802      | MAY-FY2022   | changed        | ewfew             | ewff                   | efewfwe        | ewfew             | NULL                   | 1198780.49    | 153208.27        | 230005.67             | 13141.34      | 394.20           | 0.00                  | 16.31            | 394.20              | 0.00                     | 2022-05-25 10:11:34.510 | NULL   |
+----+-----------+---------------+--------------+----------------+-------------------+------------------------+----------------+-------------------+------------------------+---------------+------------------+-----------------------+---------------+------------------+-----------------------+------------------+---------------------+--------------------------+-------------------------+--------+

I want to put all the "commentModel" columns inside the commentModel object and all the calculations inside the calculations object我想将所有“commentModel”列放在 commentModel 对象中,并将所有计算放在计算对象中

I assume Dapper is having trouble mapping eg PMNonLaborComment to your table column name.我假设 Dapper 无法将例如PMNonLaborComment映射到您的表列名称。 I suggest adding this above in every model above each property that's returning nulls for you:我建议在为您返回空值的每个属性上方的每个模型中添加此内容:

[Column(Name="column_name")]
public string? PropertyName {get; set;}

Can't claim anything yet as you've not shown your query result so that I can see what you're mapping with what.由于您尚未显示查询结果,因此无法声明任何内容,以便我可以看到您正在映射的内容。

Dapper cannot automatically map one database row to multiple objects. Dapper 不能自动将一个数据库行映射到多个对象。 You need to use multimapping and tell it where to split between the various types.您需要使用多重映射并告诉它在不同类型之间拆分的位置。 I'm assuming you want it by ProjectId.我假设您希望通过 ProjectId 获得它。

var projects = new Dictionary<int, WipCommentCalculation>();
var rows = await connection.QueryAsync<WipCommentCalculation, Calculations, CommentModel, WipCommentCalculation>(sqlStatement, parameters, commandType: commandType, splitOn:"Panonlaborcomment,Billablelabor" /* guessing with the last column name*/, (w, co, ca) => 
{
     WipCommentCalculation wip;
     if (!projects.TryGetValue(w.ProjectId, out wip))
     {
         projects.Add(w.ProjectId, wip = w);
     }
     wip.Comments.Add(co);
     wip.Calculations.Add(ca);
     return null;
});
// Use projects here and forget about the return of the query

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

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