0

下面找到一个不起作用的方法。我们在 query.Select(...

在下面找到一个具有硬编码对象属性名称的方法,该方法确实有效。但是,这种方法显然不是动态的,也不是灵活的。我可能希望搜索客户的许多属性。

错误字符串位于底部。我知道 LINQ to Entity 无法处理将 GetValue 转换为某种 TSQL 的问题。有人知道我如何编码吗?

public List<Customer> GetForQuery(params Tuple<string, string>[] keyValuePairs) {
    using (var db = new DBEntities()) {
        var availableProperties = typeof(Customer).GetTypeInfo().DeclaredProperties.ToList();
        var query = db.Customers.Select(c => c);
        foreach (Tuple<string, string> pair in keyValuePairs) { 
            PropertyInfo pi = availableProperties.First(p => p.Name.Equals(pair.Item1));
            if (pi == null)
                continue;
            query = query.Where(u => pi.GetValue(u, null).ToString().StartsWith(pair.Item2));
        }
        var results = query.Select(c => c).ToList();
        return results;
    }
}

我如何称呼上述内容:

CustomerController custController = new CustomerController();
List<Customer> results = custController.GetForQuery(Tuple.Create<string, string>("FName", "Bob" ));

工作固定方法:

public List<Customer> GetForQuery(string firstName = "", string lastName = "", string phoneNumber = "") {
    using (var db = new DBEntities()) {
        var query = db.Customers.Select(c => c);
        if (firstName.HasContent())
            query = query.Where(u => u.FName.StartsWith(firstName));
        if (lastName.HasContent())
            query = query.Where(u => u.LName.StartsWith(lastName));
        if (phoneNumber.HasContent())
            query = query.Where(u => u.EveningPhone.StartsWith(phoneNumber));
        var results = query.Select(c => c).ToList();
        return results;
    }
}

错误:LINQ to Entities 无法识别方法“System.Object GetValue(System.Object, System.Object[])”方法,并且此方法无法转换为存储表达式。

4

0 回答 0