I'd like to add a check in our repository that filters all objects out on a companyId if it's there and if it matches a given value.
So where we have:
public T First<T>(Expression<Func<T, bool>> expression) where T : EntityObject
{
var set = GetObjectSet<T>();
return set.FirstOrDefault<T>();
}
I would like to add line which looks something where...
express.And("Check for CompanyId property if it exists then make sure it = 3");
Any ideas on how to go about this?
Thanks :)
If you're looking for a function which you can use to tack on a company id check to your expression if a company id exists on the entity, this should do the trick:
You could use it like this:
And now you can call your
First
method with your expression and the companyId you want to filter by.A slightly better way to do this might be to use it as a filtering method, i.e. rewrite it as an extension method that doesn't require an inner expression and works on an object query (or IQueryable):
The beauty of this is that it will work really nicely with the stanard LINQ syntaxes (both query and fluent).
e.g. it allows queries like this:
[EDIT]
I've cleaned it up a bit and added a check on parameter visibility (must be a public, static property), as well as an ObjectQuery implementation (which will be automatically used for ObjectQuery and ObjectSet):
Bennor, Thanks so much your posting was VERY useful.
I took what you put in there and created an extension method which appends the 'And' filter to the existing expression.
Looks like a good candidate for an interface to stay away from reflection: