generic helper to get ObjectResult<T> that will match any given EntityObject

858 views Asked by At

trying to make a generic SQL Query via a method that will fetch data i was making this code

public ObjectResult<theSelectedTableNameModel> getUsersRes(string sqlStr, string ColNameAsfilter, string FiltersValue,string OrderByFilter="")
{
    string SqlCmd = "";
    string By = "";
    if (OrderByFilter.isNotEmptyOrNull())
       By = string.Concat(" ORDER BY ", OrderByFilter);
    SqlCmd = string.Format("{0} WHERE {1}={2}{3}", SqlStr, ColNameAsfilter, FiltersValue, By);


    return anEntityName.ExecuteStoreQuery<theSelectedTableNameModel>(SqlCmd);
}

i have copied my code and edited real names and other variables /parameters so i might have made a mistake, but the question is , how could i make it more generic than this ?

this is a working approach that lets me specify the query of the sqlCommand

i wanted it to fit any entity and any model/object/table

how could it be done ? i guess there's a ready solution for this or the engeniring of EF not ment to be generic... i'm using asp.net 4.0 , and latest EF..

3

There are 3 answers

0
Nilesh On

I think you need something like this

    public List<T> Get(System.Linq.Expressions.Expression<Func<T, bool>> filter = null)
    {
        IQueryable<T> query = dbSet.AsQueryable();
        if (filter != null)
        {
            query = query.Where(filter);
        }
        return query.ToList();
    }

Follow this link

0
Chintana Meegamarachchi On

why not consider passing in a collection of sql paramters in to the function call as a parameter. Once you do this, you can use any number of filters of multiple types

public ObjectResult<theSelectedTableNameModel> GetEntityBySQLCommand(string sqlStr, SqlParameter[] filterParams, string OrderByFilter="")
{
    var commandTextToExecute = OrderByFilter.isNotEmptyOrNull() ? sqlStr : string.Format(“{0} Order By {1}”, sqlStr, OrderByFilter);

    return yourObjectContext.ExecuteStoreQuery<theSelectedTableNameModel>(commandTextToExecute, filterParams);
}

Your sqlStr should look something like the following “SELECT * FROM Customer WHERE CustId = @custID and LastActiveOn = @lastActiveDate”; custID and lastActiveDate should be passed in via the SqlParameter collection (filterParams)

0
Avia Afer On

after some time of testing every possible option, while i did not find any similar code on the net..

this is my solution , as an extension method, did i conduct a bad search/research ? or just no one use it like this , although the extesion is for the type ObjectContext it does return an ObjectResult list of optional parameters for where clause + another for order by and it does the work

string firstPartSql="SELECT * FROM YourTblName"; 

list of string for WHERE filter will contain elements like

"columnName=value", "columnName Like '%val%'" 

list of string for Order by will contain elements like

"ColumnName" ,"ColumnName DESC"



 public static ObjectResult<T> getUsersResStatic<T>(this ObjectContext Entt, string sqlBeginhing, List<string> LstSelectWhersFilter = null, List<string> LstOby = null)
{


    string SqlCmd = "";
    string StrWhereFilterPrefix = "";
    string StrFinalWHEREFiter ="";
    string StrKeyOb1 = "";
    string StrKeyOb2 = "";
    string StrFinalOrderBy = "";

    if (LstSelectWhersFilter != null)
    {
        StrWhereFilterPrefix = "WHERE";
        for (int CountWhers = 0; CountWhers < LstSelectWhersFilter.Count; CountWhers++)
        {
            if (CountWhers == 0) StrFinalWHEREFiter = string.Format(" {0} {1} ", StrWhereFilterPrefix, LstSelectWhersFilter.ElementAt(CountWhers));
            else
            {
                StrWhereFilterPrefix = "AND";
                StrFinalWHEREFiter += string.Format(" {0} {1} ", StrWhereFilterPrefix, LstSelectWhersFilter.ElementAt(CountWhers));
            }

        }
    }

    if (LstOby != null)
    {
        StrKeyOb1 = "ORDER BY";
        if (LstOby.Count > 1)
        {
            StrKeyOb2 = ",";
            for (int i = 0; i < LstOby.Count; i++)
            {
                if (i == 0) StrFinalOrderBy = string.Format("{0} {1}", StrKeyOb1, LstOby.ElementAt(i));
                else
                StrFinalOrderBy += string.Format("{0} {1}", StrKeyOb2, LstOby.ElementAt(i));
            }
        }
        else StrFinalOrderBy = string.Format("{0} {1}", StrKeyOb1, LstOby.ElementAt(0));
        SqlCmd = string.Format("{0} {1} {2}", sqlBeginhing, StrFinalWHEREFiter, StrFinalOrderBy);//StrKeyOb2, ob2);
    }
    if (LstSelectWhersFilter == null && LstOby == null) SqlCmd = sqlBeginhing;

    return Entt.ExecuteStoreQuery<T>(SqlCmd);

}

any kind of comment will be helpfull (well...almost any)