简体   繁体   English

LinQ中的动态变量

[英]dynamic var in LinQ

I need something equivalent to dynamic with linq. 我需要一些与linq dynamic等效的东西。 I want to return all the active data from the type T in the database. 我想从数据库中的类型T返回所有活动数据。 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? 如何强制LinQ使用“ Activo”属性? Like using a dynamic variable 就像使用dynamic变量一样

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. 我更喜欢将实现特定属性的接口挂接到类上,然后查看我的实例(进行比较)是否实现了该接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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