非持续性只读属性正确地添加到LinqToSQL数据类

非持续性只读属性正确地添加到LinqToSQL数据类

本文介绍了如何在运行时计算的,非持续性只读属性正确地添加到LinqToSQL数据类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个日期时间字段在一个表,并在LinqToSQL数据类中的对应的属性。该任务是添加一个布尔IsWorkingTime运行时(没有映射到直接任意列,但计算在读)属性,它会说:日期时间是否为工作时间(日期部分既不是周末也不是假期,一部分时间是上午9时之间下午5点)。该物业应提供LINQ查询,但不影响后台数据库。

There is a DateTime field in a table and a mapped property in LinqToSQL data class. The task is to add a boolean IsWorkingTime runtime (not mapped to any column directly but calculated on read) property which will say whether the DateTime is a working hour (the date part is neither a weekend nor a holiday and the time part is between 9am and 5pm). The property should be available for LINQ queries but not affecting the database background.

如何实现这一目标?我使用Visual Studio数据类设计师,首先绘制模型并生成数据库即可。

How to achieve that? I use Visual Studio data classes designer to draw the model first and generate the database then.

推荐答案

至于添加的属性,你可以使用一个额外的部分类定义,将其添加到模型中。如

As for adding the property, you can utilize an additional partial class definition to add it to the model. Such as

//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。但是,如果你能得到通过后DB过滤/投影/等,您可以使用属性一旦数据已返回。

Where you will run into trouble is the part about wishing to use the property in Linq. If you want to use it for constructing a query going to the database, you may be out of luck. The provider will not be able to translate the property and its logic to the appropriate SQL. However, if you can get by with post-DB filtering/projecting/etc., you can use the property once the data has been returned.

 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

这篇关于如何在运行时计算的,非持续性只读属性正确地添加到LinqToSQL数据类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 22:43