c# - 计算的只读成员作为计算列
问题描述
我有以下课程,并希望能够使用这样的 Linq Query 来查询它dbContext.Example.Where(e=> e.IsBetween);
public class Example {
public DateTime Start {get; set;}
public DateTime End {get; set;}
public bool IsBetween => DateTime.Now >= Start && DateTime.Now <= End ;
}
但是,这会在运行时导致“无法翻译 LINQ 表达式 [...]。要么重写 [...] 要么切换到客户端评估”错误。
有什么方法可以将只读属性链接IsBetween
到数据库中的计算列?
解决方案
该错误表明 EF 无法将您的自定义方法(属性 getter)转换为 SQL。如果您有/想要映射IsBetween
到 db 中的计算列,您应该相应地进行操作。像这样的东西(没有检查 SQL 的有效性):
public class Example {
public DateTime Start {get; set;}
public DateTime End {get; set;}
public bool IsBetween {get; set;} ;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// your setup ...
modelBuilder.Entity<Example>()
.Property(p => p.IsBetween)
.HasComputedColumnSql("getdate() >= Start AND getdate() <= END");
}
如果您只想IsBetween
存在于代码中,则需要使用表达式树,或者例如:
public class Example {
public DateTime Start {get; set;}
public DateTime End {get; set;}
public bool IsBetween => _func(this) ;
public static readonly Expression<Func<Example, bool>> IsBetweenExpr = e =>
DateTime.Now >= e.Start && DateTime.Now <= e.End;
private static readonly Func<Example, bool> _func = _expr.Compile();
}
dbContext.Example.Where(Example.IsBetweenExpr) ....;
推荐阅读
- python - 找到特定的行和列并将其转换为 INT
- javafx - JavaFX TreeTableView 在行单元格中设置自定义节点
- python - 在开始学习编码/一门新语言时,有什么好的方法可以保护自己免受系统损坏?
- java - 在底部导航视图中将代码添加到片段文件
- sql - 双表问题
- c++ - 如何使用 pthreads 以正确的方式设置两个线程之一的优先级
- php - 使用PHP发送邮件未在收件箱中显示所有填写的表格
- android - 如何向服务器发布任何内容但没有使其为空
- python - 如何在python的多行字符串中使用具有不同模式的正则表达式
- mongodb - Elasticsearch MongoDB 集成工具建议