I am working on a system that the client decided to use status for the records. One of them is X开发者_运维百科 for excluded. What I want to know is if it is possible to run linq queries that adds something like
where status != 'X'
Automatically to not show "excluded" records. Thanks !
Sort of. Queries in Linq are lazily-evaluated, so you can append conditions to them as you like before actually fetching the first result and it'll still result in "optimal" SQL being used.
For example:
// an extension method on the LINQ context:
public static IQueryable<Story> FilteredStories(this DbContext db)
{
return from story in db.Stories where status != "X" select story;
}
// ...later...
var stories = from story in db.FilteredStories()
where title = "Something"
select story;
foreach(var story in stories)
{
// whatever...
}
You could also "hide" the underlying LINQ context and always go through a wrapper class that appends the status != "X"
condition. Of course, then problem with that is then you'd have to jump through hoops if you didn't want a filtered list...
What you might be after is Dynamic LINQ. It's a helper library that you can use to parse LINQ expressions from strings.
LINQ is so easy that writing the question practically gives you the answer!
where status != "X"
My preference would be
.Where(record => record.status != "X")
which does exactly the same thing. The only thing you missed is double quotes because it's a string, not a char.
精彩评论