实体框架中的多个where语句

时间:2015-09-30 02:06:41

标签: c# mysql entity-framework

数据库结构示例:

部门表 -DepartmentID

设施表 - 设施ID -DepartmentID(FK) -块 -水平 -名称 -etc

我试图使用两个where子句从EF中选择数据库。我不确定where子句出了什么问题。我被困在了。请帮忙和建议。我在互联网上搜索过,但无法找到解决方案。

        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子句选择departmentID等于SIT,以及任何块或级别或名称包含任何字母的位置。请告知我应该如何用两个where子句编写语句。谢谢!

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

查询语句的剩余部分以选择所有设施

                            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);
            }
        }

1 个答案:

答案 0 :(得分:0)

从各种Contains子句中删除“%”,它们是您不需要的SQL。

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

记住LINQ不仅仅适用于SQL!