LINQ查询,带有来自下拉列表的值以与数据进行比较

时间:2017-10-14 19:20:37

标签: c# sql-server entity-framework linq linq-to-entities

我的查询如下。有人可以帮我如何在我的Linq语句中添加dbquery吗?有评论“在这里添加”。我从昨天起就在苦苦挣扎。想法是形成一个LINQ语句并立即获取列表。谢谢。

String dbwhere = "";
if (ddlName.SelectedItem.Value != "")
{
    dbwhere = " && (User.Name == '" + ddlName.SelectedItem.Value.TrimEnd() + "')";
}
if (ddlHeightFrom.SelectedItem.Value != "")
{
    dbwhere = dbwhere + " && (Physical.Height >= '" + ddlHeightFrom.SelectedItem.Value.TrimEnd() + "')";
}
if (ddlHeightTo.SelectedItem.Value != "")
{
    dbwhere = dbwhere + " && (Physical.Height <= '" + ddlHeightTo.SelectedItem.Value.TrimEnd() + ")";
}

var usersquery = (
  from physical in dbContext.Physicals
  join user in dbContext.User on physical.UserID equals user.UserID
  join photos in dbContext.Photo on User.UserID equals photos.UserID
  where photos.PhotoNum == 1 && photos.Status == true
  // =======  Add dbwhere here ============
  select new
  {
     photos.PhotoURL,
     photos.PhotoDescription,
     user.State,
     user.Country,
     physical.EyesColor,
     physical.HairColorInfo,
     physical.HairTypeInfo,
     physical.BodyHeight,
     physical.BodyWeight,
  }).ToList();

1 个答案:

答案 0 :(得分:1)

您可以重写查询以避免将linq与SQL混合(并使其不受SQL注入的影响)

var point = CalculateIntersection(new Point(10, 50), 10, new Point(200, 70));
if (point == null)
{
    throw new Exception("no intersection between the line and the circle?");
}
myPathFigure.StartPoint = point.Value;

现在您可以添加特殊支票:

var usersquery = (
    from physical in dbContext.Physicals
    join user in dbContext.User on physical.UserID equals user.UserID
    join photos in dbContext.Photo on User.UserID equals photos.UserID
    where photos.PhotoNum == 1 && photos.Status == true
    select new
    {
        physical,
        user,
        photos,
    }; // do not put ToList here!

现在,您可以使用if (ddlName.SelectedItem.Value != "") { var userName = ddlName.SelectedItem.Value.TrimEnd(); usersquery = usersquery.Where(x => x.user.Name == userName); } if (ddlHeightFrom.SelectedItem.Value != "") { var height = int.Parse(ddlHeightFrom.SelectedItem.Value.TrimEnd()); usersquery = usersquery.Where(x => x.physical.Height >= height); } // and so on

实现数据
ToList

注意:我已将其写入记事本中,因此可能有错误。但是我希望想法很清楚