2016-01-11 34 views
6

Tôi có một phương pháp như thế này:Không thể chuyển đổi biểu thức lambda vào loại đại biểu

public ICollection<T> GetEntitiesWithPredicate(Expression<Func<T, bool>> predicate) 
{ 
      // ... 
} 

tôi làm một cuộc gọi phương thức trong lớp khác như

service.GetEntitiesWithPredicate(x => x.FoobarCollection.Where(y => y.Text.Contains(SearchText))); 

nhưng tôi luôn nhận được lỗi này:

Lambda expression cannot be converted to '<typename>' because '<typename>' is not a delegate type 

Tôi phải làm gì để thay đổi công việc này?

Edit:

tôi sử dụng Entity Framework 6 và nếu tôi sử dụng Any() thay vì ở đâu(), tôi luôn luôn chỉ nhận được 1 kết quả trở lại ... Tôi muốn vượt qua các biểu thức để EF-thực hiện của tôi:

public ICollection<T> GetEntriesWithPredicate(Expression<Func<T, bool>> predicate) 
    { 
     using (var ctx = new DataContext()) 
     { 
      return query.Where(predicate).ToList(); 
     } 
    } 
+11

Bạn có thể có nghĩa là 'Any() 'thay vì' đâu() '. 'Func ' của bạn cần trả về 'bool' nhưng' Where' đang trả về 'IEnumerable '. – haim770

+0

những thứ không tương thích. –

+1

Bạn có chắc chắn bạn có nghĩa là 'GetEntitiesWithPredicate (Expression > predicate)' và không chỉ 'GetEntitiesWithPredicate (Func predicate)'? Tại sao bạn cần 'Expression'? –

Trả lời

0
class Program 
{ 
    static void Main(string[] args) 
    { 
     var o = new Foo { }; 

     var f = o.GetEntitiesWithPredicate(a => a.MyProperty.Where(b => b.MyProperty > 0).ToList().Count == 2); // f.MyProperty == 9 true 
    } 
} 

class Foo 
{ 
    public ICollection<T> GetEntitiesWithPredicate(Expression<Func<T, bool>> predicate) 
    { 
     var t = predicate.Compile(); 

     var d = t.Invoke(new T { MyProperty = new List<Y> { new Y { MyProperty = 10 }, new Y { MyProperty = 10 } } }); 



     if (d) return new List<T> { new T { MyProperty = new List<Y> { new Y { MyProperty = 9 } } } }; 

     return null; 
    } 
} 

class T 
{ 
    public T() { } 
    public List<Y> MyProperty { get; set; } 
} 

class Y 
{ 
    public int MyProperty { get; set; } 
} 
Các vấn đề liên quan