0

我有一个简单的类:用ActiveRecord和LINQ问题查询

public class User : ActiveRecordLinqBase<User> 
{ 
    [PrimaryKey(Column = "user_id", Length = 20)] 
    public string Id { get; set; } 

    [Property(Column = "password", Length = 16)] 
    public string Password { get; set; } 
    ... 
} 

,我创建了以下存储库:

public class SqlRepository<T> : IRepository<T> where T : ActiveRecordLinqBase<T>, new() { 
    public void Add(T entity) { 
     entity.SaveAndFlush(); 
    } 

    public void Remove(T entity) { 
     entity.DeleteAndFlush(); 
    } 

    public void Modify(T entity) { 
     entity.UpdateAndFlush(); ; 
    } 

    ... 

    public IEnumerable<T> FindAll(Func<T, bool> predicate) { 
     return ActiveRecordLinqBase<T>.Queryable.Where(predicate); 
    } 
} 

现在,运行下面的单元测试(针对MySQL数据库时):

[Test] 
public void Test_Sample() { 
    var repo = new SqlRepository<T>(); 
    repo.Add("john.doe", "keyword1"); 
    repo.Add("other.user", "keyword2"); 

    var users = repo.FindAll(x => x.Username.Contains("john")).ToList(); 

    Assert.AreEqual(1, users.Count); 
} 

...我碰到下面的SQL查询:

选择this_.user_id为user1_0_0_,this_.password为password0_0_,this_.role作为role0_0_来自用户的THIS_

哪里WHERE条款?

如果我这样做,而不是直接在相同的测试下...

var users = User.Queryable.Where(x => x.Username.Contains("john")); 

我碰到下面的SQL:

选择this_.user_id为user1_0_0_,this_.password为password0_0_, this_.role作为role0_0_来自用户的THIS_ WHERE this_.user_id喜欢P0;?P0 = '%约翰%'

难道我做错了什么?

这两个查询有什么区别?


编辑:我也试图与

return ActiveRecordLinq.AsQueryable<T>().Where(predicate); 

没有成功。

回答

3

现在这仅仅是因为我喜欢的代码,有时我看到的东西......我在活动记录方面的专家,所以这只是一个猜测...

也许你应该改变的签名从

public IEnumerable<T> FindAll(Func<T, bool> predicate) 

FindAll方法为

public IEnumerable<T> FindAll(Expression<Func<T, bool>> predicate) 

,这将使你打的Where权过载,这是最利k你正在寻找的超载。

这是因为Func不能以与Expression of Func相同的方式反映出来。

+0

花了大约2.5小时:/非常感谢你;) –