Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

If you create a Filter object that contains criteria for Linq that normally goes in a where clause like this:

 var myFilterObject = FilterFactory.GetBlank();
 myFilterObject.AddCondition("Salary", "lessThan", "40000");

 var myResult = myRepository.GetEmployees(myFilterObject);

How would you match the Linq field to the Field Name without using a big case statement?

 return from e in db.Employee
        where e.Salary < 40000
        select new IList<EmployeeViewModel> { Name= e.name, Salary= e.Salary };

I assume you need to send an object to the Repository that specifies filtering so that you only pull what records you need. I assume Linq doesn't pre-compile (unless you create a customized delegate and function), so you should be able to dynamically specify which fields you want to filter.

It would be nice if you could do something like e["Salary"] like some type of Expando Object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
370 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can build the Expression by hand, like so:

var eParam = Expression.Parameter(typeof(Employee), "e");

var comparison = Expression.Lambda(
    Expression.LessThan(
        Expression.Property(eParam, "Salary"),
        Expression.Constant(40000)),
    eParam);

return from e in db.Employee.Where(comparison)
       select new EmployeeViewModel { Name = e.name, Salary = e.Salary };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...