Question

I'm developing a small Windows Store App and i'm using sqlite-net

I got a db of persons, each person has a name, id, sex etc etc

In my project there is a View to search inside this db. The user can insert one or multiple information to search.

So, i build the search object (OPerson) and i want to use that to reach the goal.

Now i made a function for every property of the person like "searchById" "searchByName" and so on.. at last i combine that functions to get the results

Is possible to create an unique method using the power of sqlite-net, in wich all is concatenated?also the checking of some attribute's value

If i pass an object OPerson

Id = null
Name = John
Age = null
Sex = male

Is possible to write a query to reach that goal? Something like this pseudo-code

pers = (from p in db.Table<Persons>() 
                     where (if OPerson.Id !=null) p.Id==OPerson.Id}
                     AND {(if OPerson.Name !=null) p.Name.Contains(OPerson.Name)}
                     AND {(if condition) where-contion}
                     select p).ToList();
Was it helpful?

Solution

I'd recommend building your query in several steps. This way you can take the conditions to outside the query which makes it cleaner and also gives you more control. Something like this:

var pers = from p in db.Table<Persons>() 
           select p;

if(OPerson.Id !=null)
    pers = pers.Where(p => p.Id==OPerson.Id);
if(OPerson.Name !=null)
    pers = pers.Where(p => p.Name.Contains(OPerson.Name);
....
....
var results = pers.ToList();

This code still generates one single query that is only executed once when you call the ToList() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top