简体   繁体   中英

Multiple where statements in Entity Framework

Database structure sample:

Department Table -DepartmentID

Facility Table -Facility ID -DepartmentID (FK) -Block -Level -Name -etc

I am trying to select from database from the EF using two where clause. I am not sure what went wrong at the where clause. I am stuck at it. Please help and advice. I have googled on the internet but cannot find the solution to it.

        string departmentID = "SIT";
        string block = "L";
        string level = "4";
        string name = "L.425";

        using (var db = new KioskContext())
        {
            var facilitys = from f in db.Facilitys

Where clause to select departmentID where equals to SIT and also where any block or level or name contains any alphabets. Please advice how should i write the statement with two where clause. Thank You!

                            where f.Department.DepartmentID == departmentID
                            && (f.Block.Contains("%" + block + "%") || f.Level.Contains("%" + level + "%")
                            || f.Name.Contains("%" + name + "%"))

Remaining of the query statement to select all the facilities

                            orderby f.FacilityID
                            select new
                            {
                                f.FacilityID,
                                f.DepartmentID,
                                f.Description,
                                f.Block,
                                f.Level,
                                f.Name,
                                f.OpenHours,
                                f.CloseHours,
                                f.MaxBkTime,
                                f.MaxBkUnits,
                                f.MinBkTime,
                                f.MinBkUnits
                            };
            foreach (var fac in facilitys)
            {
                FacObject facobject = new FacObject(fac.FacilityID, fac.DepartmentID, fac.Description, fac.Block, fac.Level,
                    fac.Name, fac.OpenHours, fac.CloseHours, fac.MaxBkTime, fac.MaxBkUnits, fac.MinBkTime, fac.MinBkUnits);
                sqlFacList.Add(facobject);
            }
        }

Remove the "%" from the various Contains clauses, they are SQL cruft you do not need.

where f.Department.DepartmentID == departmentID
     && (f.Block.Contains(block) 
     || f.Level.Contains(level)
     || f.Name.Contains(name ))

Remember LINQ is not just for SQL!

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