entity-framework - 使用嵌套 DTO 获取嵌套数据并锐化到 DTO
问题描述
一般来说,我是 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' 方法,并且此方法无法转换为存储表达式。
解决方案
您不能完全执行此查询,最好进行两个简单查询,然后在客户端处理它们的结果:
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();
推荐阅读
- android - 有没有办法将Textview上的动画保存为android中的.gif文件?
- python - Django - 将更新的信息保存到现有用户
- python - 编写一个 Python 程序来打印以下数字序列(N 由用户输入):X + X^3/3!+ X^5/5!... 直到第 N 项
- javascript - Javascript 中的 ctrlKey 事件
- java - 如何在通过 flink cli 运行的 flink 应用程序 jar 中指定外部属性文件
- microservices - 有关聚合的详细信息以及在何处使用聚合
- c# - 如何在wpf c#中单击按钮时在窗口中打开特定部分
- sql - 对候选组使用 HAVING 子句时将评估哪一行?
- shell - 如何将回声值分配给shell脚本中的变量
- flutter - 如何在列中创建 listview.builder?