简体   繁体   中英

dynamic var in LinQ

I need something equivalent to dynamic with linq. I want to return all the active data from the type T in the database. The problem is that not all the tables have an "Active". So i need something like:

public static List<T> get<T>() where T : class
{
    if (typeof(T).GetProperty("Activo")!=null)
    {
        return (from c in context.Set<T>().AsQueryable()
                where c.Activo //I know for sure it have an Activo property
                select c).ToList();
    }
    else
    {
    return (from c in context.Set<T>().AsQueryable()
            select c).ToList();
    }         
}

How can I force LinQ to use the "Activo" property? Like using a dynamic variable

An interface is not possible because i need to pass to the method type that are unable to implement it

You have to use

public static List<T> get<T>() where T : class
{
    var type = typeof(T);
    var prop = type.GetProperty("Activo")
    if (prop!=null)
    {
        return (from c in context.Set<T>().AsQueryable()
            where prop.GetValue(c, null)=="xyz123"
            select c).ToList();
    }
    else
    {
        return (from c in context.Set<T>().AsQueryable()
            select c).ToList();
    }         
}

I don't like using reflection, though, because if you ever change the property's name, reflection code will break. I prefer to hook an interfact implementing a particular property to the class, and then see if my instance (to compare) implements that interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM