简体   繁体   中英

How to use where clause with different data in one column in entity framework?

public ActionResult Index()
   {
     var results = db.Employee
        .Where(d => d.JOBID == "Tester" 
            && d.JOBID == "Developer" 
            && d.Salary =="2000")
        .ToList();

     return View(results);
  }

Results

NAME JOBID SALARY

  1. John Tester 4000
  2. joy Developer 2000

if you want to apply selection of two values from the same column you'd better use OR operator, This will list either Tester or Developer whom their salary is exactly 2000

public ActionResult Index()
   {
     var results = db.Employee
        .Where(d => 
                    (d.JOBID == "Tester" || d.JOBID == "Developer") && 
                    d.Salary =="2000")
        .ToList();

     return View(results);
  }

If you want to use the Where clause to select from one column based on multiple values, put the values you are looking for into a list first:

var jobIdList = new List<string>();

jobIdList.Add("Tester");
jobIdList.Add("Developer");

Now you can use the Contains clause to query any results that have a value in that list.

 var results = db.Employee
    .Where(d => (jobIdList.Contains(d.JOBID) 
        && d.Salary =="2000"))
    .ToList();

This way your query always works the same, but you can change the results you get by changing the values in jobIdList . Want to include Managers? jobIdList.Add("Manager"); , then run your query again. Now you want to remove Developers and only get back Testers and Managers? jobIdList.Remove("Developer") , then run your query and get new results. This makes your query method much more flexible. Now you get back any employee where the JOBID is in the list AND the salary = 2000. (you might look at that salary value, hard coding that might not be ideal.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM