How to correctly add a runtime-calculated, non-per

2019-07-10 16:53发布

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.

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

1条回答
欢心
2楼-- · 2019-07-10 17:31

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
{
    // ...
}

And then your extension

//TheModelCustom.cs
public partial class TheModel
{
     public bool IsWorkingTime
     {
          get
          {
               // your (hopefully inexpensive) logic
          }
     }
}

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
查看更多
登录 后发表回答