Search code examples
c#sql-serverentity-frameworklinqlinq-to-entities

LINQ query with value from dropdown to compare with data


My query is below. Can someone help me how to add dbquery inside my Linq statement? There is a comment "Add Where here". I'm struggling since yesterday. Idea is to form a LINQ statement and get the list at once. Thank you.

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

Solution

  • You can rewrite your query to avoid mixing linq with SQL (and make it safe from SQL injections)

    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!
    

    Now you can add your special checks:

    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
    

    Now you can materialize your data with ToList

    var result = usersquery.Select(x => new 
      {
        x.photos.PhotoURL,
        x.photos.PhotoDescription,
        x.user.State,
        x.user.Country,
        x.physical.EyesColor,
        x.physical.HairColorInfo,
        x.physical.HairTypeInfo,
        x.physical.BodyHeight,
        x.physical.BodyWeight
      }).ToList();
    

    NOTE: I've write it in notepad, so it may have errors. However I hope idea is clear