Dynamic Linq from string with EF I wrote an EF browser to dynamically navigate through entities. Beside basic properties of system types, each entity can have several singular or plural navigation properties. In order to support all of these using a single batch of code, I come up with the following solution considering the following requirement:


Each entity has an integer ID primary key.


Sample query strings (Person is an entity (ID = 10) with Job and Cars navigation property):


Person/10/Job

Person/10/Cars



Solution:

public List&lt;dynamic&gt; LoadEntitiesByQuery(String query) {

    String[] parts = query.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
    String entityName = parts[0];
    int id = int.Parse(parts[1]);
    String subEntityName = parts[2];

    Type entityType = GetTypeFromEntityName(entityName);

    var tempObj = db.Set(entityType)
                    .AsQueryable()
                    .Where(String.Format("ID == {0}", id))
                    .FirstOrDefault();

    var propertyInfo = tempObj.GetType().GetProperty(subEntityName);

    List&lt;dynamic&gt; objects;

    if (propertyInfo.PropertyType.IsGenericType)
        objects = ((IEnumerable&lt;dynamic&gt;)propertyInfo.GetValue(tempObj, null)).ToList();
    else
    {
        var tr = propertyInfo.GetValue(tempObj, null);
        objects = new List&lt;dynamic&gt;();
        objects.Add(tr);
    }

    return objects;
}

internal static Type GetTypeFromEntityName(string entityName)
{
    Type entityType = null;
    switch (entityName)
    {
        case "Person":
            entityType = typeof(Person);
            break;
        case "Job":
            entityType = typeof(Job);
            break;

        ///  ....
    }
    return entityType;
}


I'm looking for faster ways of doing dynamic query instead of reflection.
I would write an extension method to do parsing of input string. so it should not be inside  your query method.
I have declared a class named SearchCriteria to encapsulate all data member you want t o query.


this is just a first set of refactoring which should be included.

public class SearchCriteria
{
    public Type EntityType { get; set; }

    public string SubEntityName { get; set; }

    public int EntityId { get; set; }

}

public static class ParseExtension
{
    public static SearchCriteria Parse(this string query)
    {
        string[] parts = query.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        var entityName = parts[0];
        var id = int.Parse(parts[1]);
        var subEntityName = parts[2]; 

        return new SearchCriteria
        {
            EntityType = GetTypeFromEntityName(entityName),
            EntityId = id,
            SubEntityName = subEntityName
        };
    }

    private static Type GetTypeFromEntityName(string entityName)
    {
        Type entityType = null;
        switch (entityName)
        {
            case "Person":
                entityType = typeof(Person);
                break;
            case "Job":
                entityType = typeof(Job);
                break;
        }
        return entityType;
    }
}


public List&lt;dynamic&gt; LoadEntitiesByQuery(SearchCriteria query)
{
    Type entityType = query.EntityType;

    var tempObj = db.Set(entityType)
                    .AsQueryable()
                    .Where(string.Format("ID == {0}", query.EntityId))
                    .FirstOrDefault();

    var propertyInfo = tempObj.GetType().GetProperty(query.SubEntityName);

    List&lt;dynamic&gt; objects;

    if (propertyInfo.PropertyType.IsGenericType)
        objects = ((IEnumerable&lt;dynamic&gt;)propertyInfo.GetValue(tempObj, null)).ToList();
    else
    {
        var tr = propertyInfo.GetValue(tempObj, null);
        objects = new List&lt;dynamic&gt;();
        objects.Add(tr);
    }

    return objects;
}