Entity framework dynamically "contains" search a field by type in database

541 views Asked by At

Instead of the following code....:

public List<myUsers> SearchField(string search, string searchfield, int count = 15)
{
    IQueryable<myUsers> DCs = this.entities.myUsers;

    if (!String.IsNullOrWhiteSpace(search))
    {
       var DC2 = DCs;
       if (searchfield == "userid")
       {
         DC2 = ListUtility.WhereInt(DCs, searchfield, search, 0);
         // custom function to Contain-search an integer with Relfection
       }
       else if (searchfield == "username" || searchfield == "Lastname" || searchfield == "Firstname" || searchfield == "email")
       {
         DC2 = ListUtility.WhereStringContains(DC2, searchfield, search);
         // custom function to Contain-search a string with REFLECTION
       }
       else if (searchfield == "date" || searchfield == "lastupdated")
       {
        // dates are impossible to work with--here's a function 
        // I don't know how to implement
        DC2 = DateContainsSearch(DCs, searchfield, search);
       }
        return DC2.Take(count).ToList();
   }
   else
   {
      return new List<myUsers>();
   }
}

I want to be able to design a function that looks like the code below, based on T type of entity... AND based on a "SearchClass" that has USER-SUBMITTED PRE-POPULATED string fields "searchText", "searchField", "searchType" (I don't know if we should need this last one) :

public IQueryable<T> Search<T>(ref IQueryable<T> table) where T: class
    {
        foreach (SearchClass s in si)
        {
            table = table.WhereAnyType<T>(s.searchText, s.searchField, s.searchType); // all parameters are string
        }
        return table;
    }

I am looping through the "SearchClass" LIST "si" because there may be combined searches... such as Where firstname.contains("bob") AND username.contains("Bob99")

In other words, I wish we can treat every field in the database like a string.

Even with reflections I have so much trouble making something like this.

0

There are 0 answers