I frequently need to limit SELECTs by fields like publishStart, publishEnd, active
I have these fields in several different tables. So only rows should be selected, that are
a: active == true;
b: publishStart < now;
c: publishEnd > now;
So, for example:
db.myTable.SingleOrDefault(a => (a.ID == _theID
//now the active and start-end part:
&& ((a.publishEnd > DateTime.Now) || (a.publishEnd == null))
&& ((a.publishStart <= DateTime.Now) || (a.publishStart == null))
&& a.active == true));
This is a bit lengthy, so I wonder if it is possible to create a (extension?)-method like:
db.myTable.SingleOrDefault(a => (a.ID == _theID).isActive()
where the isActive() provides the 3 lines of the above snippet.
How could I do this?
Is there a better way to clean up code?
To define an extension you need a static class. You can put this in whatever namespace you like, just remember to include it in your usings.
Notice
YourEntityTypein there. This is used to ensure the method is aware of the existence ofpublishStart,publishEnd, andactive. This should be either the class that implements these fields or a contract (interface) that defines them.You would then call this like so:
More on extension methods here: http://msdn.microsoft.com/en-us/library/bb383977.aspx
As there are lots of comments popping up all over the place, I’m going to add here a brief explanation of the interface solution…
It’s unclear in the question whether or not there is a common implementation for the three filtered fields or an interface to define them. If not, for the above to work, you will not either:
YourEntityTypewithYourBaseEntityType.YourEntityTypewithIYourContract.