问题描述
|
表中有一个DateTime字段,LinqTosql数据类中有一个映射的属性。任务是添加一个布尔IsWorkingTime运行时(不直接映射到任何列,而是根据读取进行计算)属性,该属性将说明DateTime是否是工作时间(日期部分既不是周末也不是假日,并且时间部分是在上午9点之间)和下午5点)。该属性应可用于LINQ查询,但不影响数据库背景。
如何实现呢?我使用Visual Studio数据类设计器首先绘制模型,然后生成数据库。
解决方法
至于添加属性,您可以利用附加的局部类定义将其添加到模型中。如
//TheModel.cs
// file generated by tool
public partial class TheModel
{
// ...
}
然后你的扩展
//TheModelCustom.cs
public partial class TheModel
{
public bool IsWorkingTime
{
get
{
// your (hopefully inexpensive) logic
}
}
}
您希望在Linq中使用该物业的部分会遇到麻烦。如果要使用它来构造去数据库的查询,则可能不走运。提供程序将无法将属性及其逻辑转换为适当的SQL。但是,如果可以通过数据库后过滤/投影/等方式获得帮助,则可以在返回数据后使用该属性。
var results = (from model in db.TheModels
where /* some criteria */
select model) // <-- the part of the query that goes to the DB
.AsEnumerable()
.Where(m => m.IsWorkingTime); // <-- happens in memory