我想对我的以下模型的最后一条记录执行条件:
public partial class TestPart
{
public int Id { get; set; }
public int TestId { get; set; }
public int Status { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
}
查询:
var query = context.TestPart.OrderByDescending(tp=>tp.Id)
.Take(1)
.Where(tp => tp.TestId == 100 &&
tp.Status == 1 &&
tp.Jobs.All(j => j.Type == "Recurring")
这里我想获取 TestPart 的 ID,其 status = 1 并且所有作业都在重复
,但这应该只考虑检查测试部分的最后记录
但我无法在上述查询中选择最后一个 TestPart 的 Id。
更新:
Id TestId Status
1 100 1
2 100 2
3 100 0
4 100 1
5 101 1
所以在这里我想根据 TestId 过滤掉数据,然后为该特定测试选择最后一条记录,然后检查是否所有作业类型都针对最后选择的 TestPart id 重复出现,即在上述情况下 TestPartId = 4。
最佳答案
解释有点支离 splinter 。为了确保我回答的是正确的问题,以下是我的假设:
- 一个
Test
有很多TestPart
child 。 - 您需要给定测试的最后一个
TestPart
,而不仅仅是表的最后一个条目(无论测试 ID 是什么)。 - 您要确定最后一项是否符合条件,从而使代码的最终结果成为 bool 值。
您需要在此处拆分数据检索和数据验证步骤。
合并它们时,会得到不同的结果。您要求最后一个符合条件的项目。这意味着在包含 10 个项目(按时间顺序编号为 1 到 10)的列表中,如果符合条件,您最终可能会得到项目 8,而第 9 和 10 项不符合条件。
根据您的描述,我推测这不是您想要的。你想取10项(不管它是否符合条件,只有这样检查这个项是否符合条件。
这样想:
- I want the last person named John who entered this building.
- I want to see if the last person who entered the building is named John.
您的代码正在尝试做第一个。但你真正想做的是第二个。
您的代码的正确版本:
//Get the last testpart of the test.
TestPart item = context.TestPart
.Include(tp => tp.Jobs) //possibly optional dependent on lazy/eager loading.
.OrderByDescending(tp=>tp.Id)
.First(tp => tp.TestId == 100);
//Check if this item fits the criteria
bool isValid =
item.Status == 1
&& item.Jobs.All(j => j.Type == "Recurring");
isValid
包含您的答案。
编辑 - 只是为了完整性
有多种方法可以将其合并到一个查询中,但这会使代码容易被误解。
bool isLastItemValid = context.TestPart
.Where(tp => tp.TestId == 100)
.OrderByDescending(tp => tp.Id)
.Take(1)
.Any(tp =>
tp.Status == 1
&& tp.Jobs.All(j => j.Type == "Recurring");
这会给您相同的结果。它依赖于在只有一项的列表上调用 Any()
实际上只评估一项的“技巧”。
虽然在技术上是正确的,但我发现这个版本不必要地复杂,可读性差,并且更容易被开发人员误解。
关于c# - 对表的最后一条记录执行条件并获取该记录的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49935958/