I'm using ServiceStack.OrmLite
v4.0.62 because of .NET Framework 4.0. I need to perform search functionality. As my POCO classes have deep hierarchy, I need to use LINQ queries with nested subqueries. E.g.:
// some code is omitted
Expression<Func<Person,bool>> condition = p => p.Name.Contains("John") &&
p.Addreses.Any(adr => adr.City.Contains("Moscow") &&
adr.Street.Contains("Yuri Gagarin") &&
adr.Building == 23); // and so on...
// some code is omitted
// Gets the quantity of records were found
public int GetCountBy(Expression<Func<T,bool>> condition)
{
// here it throws an Exception
return db.Persons.Count(condition);
}
And now it throws an Exception:
variable 'person' of type 'Reestr.DAL.Entities.Person' referenced from scope '', but it is not defined
Same exception is thrown when we use another method which supports Expression as parameter. My questions are: How can I solve that problem? Does OrmLite supports such queries?
As far as I understand there is no such possibility in the OrmLite version I've chosen. But I found that OrmLite supports inner lambdas if they are expressed using
Sql
class. We could rewrite our previous example in such way:And it works fine) Moreover we could add some nested lambda in Address also. So I decided to implement ExpressionVisitor class to remap lambdas. First of all I want to show my PersonRepository class which inherits generic implementation of standard IRepository interface:
And a class that is responsible for remapping:
So also I've created two attributes that you could see in the code above, they are:
CustomPrimaryKeyAttribute
andCustomForeignKeyAttribute
. They are empty classes, that are used for properties or fields that aren't in standard OrmLite meaning of keys (because as I know OrmLite doesn't support custom foreign keys or custom primary keys, not followed by name convention or Id). Now everything works fine. Of course, I understand that this is not the best solution and it isn't so elegant as I want it to be. I'd like that you watch on this solution and tell me what could I improve or give me some advices I will be glad to hear them from you.