c# - 如何在 EF Core 5 请求中使用未映射的属性
问题描述
我需要在代码中的许多地方使用一种条件(前端也是如此)。我保持这种情况就像模型中的属性一样。问题是将此属性用于 EF 核心请求,因为无法翻译。
简化示例(实际情况更复杂):
public class Job
{
public DateTime? StartTime{get;set;}
public DateTime? EndTime{get;set;}
public bool Enabled{get;set;}
public bool IsRunning
{
get{ return !EndTime.HasValue && Enabled }
}
}
public class Repository
{
public List<Job> GetRunningJobs
{
_context.Jobs.Where(j => j.IsRunning).ToList();
}
}
最好的方法是什么?谢谢
解决方案
你必须写好你的linq查询
public class Repository
{
public List<Job> GetRunningJobs()
{
using(AppContext _context = new AppContext())
{
return _context.Jobs.Where(j => j.IsRunning == true && j.EndTime != null )
.ToList();
}
}
}
另一种方法是你可以有另一个类,即 JobDto(数据传输对象)
public class JobDto
{
public DateTime? EndTime{get;set;}
public bool Enabled{get;set;}
}
public class Repository
{
public List<JobDto > GetRunningJobs()
{
using(AppContext _context = new AppContext())
{
IQueryable<JobDto> list;
list = from i in appContext.Jobs
where i.IsDeleted == null
&& u.IsRunning == true
&& u.EndTime != null
select new JobDto (){
EndTime= i.EndTime//set other stuff
};
return list.ToList();
}
}
}
推荐阅读
- c# - 如何将一个对象的数据分配给另一个继承自原始对象的不同类型的对象?
- scala - 尽管 DataFrame 相等,但相同元素和“==”返回不相等
- r - 在混合方差分析中计算 Omega² 和部分 Omega²
- javascript - For循环TypeScript中的所有值都替换为最后一个值
- apache-spark - 在纱线杀死执行程序后,Spark 不断重新启动执行程序
- c# - 如何使用委托在 C# 中实现委托模式?
- shell - 如何解压缩“.zip”存档并使用 Perl 将输出重定向到指定文件?
- ios - 检测目标视图控制器中的导航弹出
- c# - 重生的 Prefab 实例不会在碰撞时破坏
- ssl - 即使应用了重定向,WWW 子域也不安全