【问题标题】:Fill DTO from two distinct objects从两个不同的对象填充 DTO
【发布时间】:2021-12-27 21:25:36
【问题描述】:

我有以下 DTO:

public int IdTableOne { get; set; }
public string ValueTableOne { get; set; }
public int IdTableTwo { get; set; }
public string ValueTableTwo { get; set; }

另外,我有两个模型(TableOne 和 TableTwo),我将这些模型填充到我的存储库中,执行以下代码:

return dbContext.TableOne;

此时一切正常。 TableOne 和 TableTwo 已填充,但现在我想将这些值的组合返回到我的 DTO 对象中(TableOneId 等于 TableTwoId,这是两个表之间的关系)为此我正在尝试这样的事情:

public IEnumerable<TableOneAndTwoDTO> GetTableOneAndTwo()
{
    List<TableOneAndTwoDTO> combination = new List<TableOneAndTwoDto>();
    var t1 = myRepository.GetTableOne();
    var t2 = myRepository.GetTableTwo();

    var query = from p in t1
        select new {
            IdTableOne = p.Id,
            ValueTableOne = p.Value,
        };

    foreach (var item in query)
    {
        combination.Add(new TableOneAndTwoDTO { IdTableOne = item.IdTableOne, ValueTableOne = item.ValueTableOne });
    }
}

所以我的问题是,只有在 IdTableOne = IdTableTwo 时,我才能将 TableTwo 值添加到我的 DTO。

【问题讨论】:

    标签: c# linq entity-framework-core asp.net-core-webapi


    【解决方案1】:

    您可以加入您的表格结果。像这样的:

    var query = from p in t1
                join j in t2 on p.IdTableOne equals j.IdTableTwo
                select new { p, j };
    

    然后您可以使用以下方式将连接值添加到您的 DTO:

    foreach (var item in query)
    {
        combination.Add(new TableOnwAndTwoDTO { IdTableOne = item.p.IdTableOne, IdTableTwo = item.j.IdTableTwo... })
    }
    

    【讨论】:

    • 为什么要处理来自 j 对象的空结果? join 不会给你留下空值:它不等同于 SQL LEFT JOIN。
    • @StriplingWarrior Rigth!感谢您的评论,我正在考虑做一些左加入。
    【解决方案2】:

    只需执行 LINQ Join。通过将整个内容放入一个查询中,然后在返回之前调用.ToList(),您可以避免原始代码中的许多仪式。

    public IEnumerable<TableOneAndTwoDTO> GetTableOneAndTwo()
    {
        var t1 = myRepository.GetTableOne();
        var t2 = myRepository.GetTableTwo();
        var combination =
            from p in t1
            join j in t2 on p.IdTableOne equals j.IdTableTwo
            select new {
                IdTableOne = p.Id,
                ValueTableOne = p.Value,
                IdTableTwo = j.Id,
                ValueTableTwo = j.Value,
            };
         return combination.ToList();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-22
      • 2011-09-20
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 2013-04-18
      相关资源
      最近更新 更多