使用嵌套DTO获取嵌套数据并锐利进入DTO

问题描述 投票:1回答:2

我是EF,Linq和C#的新手一般,我坚持开发以下。我无法将数据映射到这样的结构:

Id,
Actions [
  Action1,
  Action2,
  Action3
]

我有2个像这样的DTO类:

public class TestDTO
{
    public int TestId { get; set; }
    public TestDTO2[] Actions { get; set; }
}

public class TestDTO2
{
    public int TestActionId { get; set; }
    public DateTime? StartDate { get; set; }
    ...
}

我将对DB的调用分离到名为BusinessLogic的文件中,我这样做:

    public IQueryable<TestDTO> GetNested(Filter filter)
    {
        var query =
                    from a in db.Table1.AsQueryable()
                    select new TestDTO
                    {
                        TestId = a.Id,
                        Actions = (
                            from b in db.Table2.AsQueryable()
                            where a.Id == b.TestId 
                            select new TestDTO2
                            {
                                TestActionId = b.TestActionId,
                                StartDate = b.StartDate
                            }
                        ).ToArray()
                    };
        return query;
    }

我收到以下错误:

LINQ to Entities无法识别方法'Project.Core.Models.TestDTO2 [] ToArrayTestDTO2'方法,并且此方法无法转换为存储表达式。

entity-framework linq dto
2个回答
2
投票

您不能完全执行此查询,最好是进行两个简单的查询,然后在客户端处理它们的结果:

var main = db.Table1.Select(x => new { x.Id, x.Title }).ToList();
var mainIds = main.Select(x => x.Id).ToList();
var actions = db.Table2.Where(x => mainIds.Contains(x.TestId)).Select(x => new 
{ 
    x.TestId,
    x.TestActionId, 
    x.StartDate
}).ToList();

var result = main.Select(x => {
    var actions = actions.Where(y => y.TestId == x.Id).Select(y => new TestDTO2
                  {
                      TestActionId = y.TestActionId,
                      StartDate = y.StartDate
                  }).ToArray();
    return new TestDTO 
    { 
        TestId = x.Id, 
        Title = x.Title, 
        Actions = actions.Length == 0 ? null : actions
    };
}).ToList();

1
投票

是的,你不能使用任何无法在EF中翻译sql的c#方法。实际上,您需要获取一个列表,然后将其转换为您的DTO

 db.Table1
   .Join(db.Table2,
   a => a.Id,
   b => b.TestId,
   (a, b) => new
   {
      a.Id,
      b
   })
   .GroupBy(k => k.Id, v => v).ToList()
   .Select(a=>new TestDTO
       {
         TestId = a.Id,
         Actions = a.Select(b=>
         new TestDTO2
           {
              TestActionId = b.TestActionId,
              StartDate = b.StartDate
           }.ToArray()
         }).ToList()
© www.soinside.com 2019 - 2024. All rights reserved.