c# – Lambda表达式转换

我该如何施展

Expression<Func<T, bool>> predicate

Expression<Func<SomeType, bool>> predicate

到目前为止找不到办法.或者至少创建一个新的表达式< Func< SomeType,bool>>通过使用谓词的第一个字符串表示.

如果有帮助,T仅限于实现ISomeInterface的类型,而SomeType实现它.

LE:进一步澄清

界面如下:

public interface ICacheable
{
    List<T> GetObjects<T>(Expression<Func<T, bool>> predicate) where T : ICacheable;
}

那你有

public partial class Video : ICacheable
{
    public List<T> GetObjects<T>(Expression<Func<T, bool>> predicate) where T : ICacheable
    {
        // implementation here that returns the actual List<Video>
        // but when I try to query the dbcontext I can't pass a predicate with type T, I have to cast it somehow
        List<Video> videos = db.Videos.Where(predicate).ToList(); // not working
    }
}

那么你有:

public class RedisCache
{
    public List<T> GetList<T>(Expression<Func<T, bool>> predicate) where T : ICacheable
    {
        List<T> objList = // get objects from cache store here
        if(objList == null)
        {
            List<T> objList = GetObjects<T>(predicate);
            // cache the result next
        }
        return objList;
    }
}

我在任何类中都使用上面的代码:

// If the list is not found, the cache store automatically retrieves 
// and caches the data based on the methods enforced by the interface
// The overall structure and logic has more to it. 
List<Video> videos = redisCache.GetList<Video>(v => v.Title.Contains("some text"));
List<Image> images = redisCache.GetList<Image>(v => v.Title.Contains("another text"));

我会将此扩展到我需要可缓存的任何类型的对象,其方法允许Cache存储自动检索实体或实体列表(如果在缓存中找不到它们).我可能会这样做完全错了.

最佳答案 我不是在实体框架上划线,但我知道LINQ中的DatabaseContext有一个GetTable< T>它返回基于泛型的表.如果“
GetTable equivalent for ObjectContext”可以通过,它也可以在EF中使用?

要使您的语句真正通用,您可以尝试这样做:

public MyBaseObject<T>
{
    public List<T> GetObjects<T>(Expression<Func<T, bool>> predicate) where T : ICacheable
    {
        return db.CreateObjectSet<T>().Where(predicate).ToList();
    }
}

public partial class Image : MyBaseObject<Image>, ICacheable
{
}

public partial class Video : MyBaseObject<Video>, ICacheable
{
}
点赞