none
Generics Query To Retrieve Rows By Column RRS feed

  • Question

  • I'm sure there is a better way to do this, but I'm not familiar enough with L2S (or generics) to know what the alternative is. I want a generic (no pun intended) way to query any table associated with a context by some column name and column value. The following query works, but based on the generated SQL code, it simply retrieves all rows from the table and filters rows not matching the criteria. This is obviously not optimal. Can someone suggest a better approach?

    Here is the code:

     

    public static IList<T> GetByColumnName<T>(DatabaseContext database, string columnName, string columnValue) where T : class
    {
    string dataType;

     

    // Get the table by the type passed in
    var table = database.GetTable<T>();

     

    // Get the metamodel mappings so I can get at the column definitions.
    MetaModel modelMap = table.Context.Mapping;

     

    // Get all the data members (columns)
    ReadOnlyCollection<MetaDataMember> dataMembers = modelMap.GetMetaType(typeof(T)).DataMembers;

     

    // Find the desired column so I can get its data type
    var
    qry = from d in dataMembers
    where d.MappedName == columnName
    select d;

    dataType = qry.SingleOrDefault().Type.Name;

     

    return table.SkipWhile<T>(delegate(T t)
    {
    switch (dataType.ToLower())
    {

     

    case "int32":
    int intValue = Int32.Parse(t.GetType().GetProperty(columnName).GetValue(t, null).ToString());
    return intValue != Int32.Parse(columnValue);

     

    case "string":
    string stringValue = t.GetType().GetProperty(columnName).GetValue(t, null).ToString();
    return stringValue != columnValue;

     

    default:
    return false;
    }
    }).ToList<T>();
    }

    Wednesday, October 7, 2009 9:01 PM

Answers

All replies