LINQ查询从下拉列表中值数据
问题描述:
我的查询低于比较。有人可以帮助我如何在我的Linq语句中添加dbquery吗?有一条评论“Add Where here”。我从昨天开始挣扎。想法是形成LINQ声明并立即获取列表。谢谢。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();
答
你可以重写查询以避免混合SQL LINQ(并使其从SQL注入安全)
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
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();
注:我已经写在记事本中,所以它可能有错误。不过,我希望的想法是明确
困难的部分是将有大量的数据,并希望这是好的有没有减慢加载时间我会尽力。谢谢。 – dotNETEngineer
@dotNETEngineer当你第一次创建'usersquery'时没有发生实际的数据获取。数据将在应用所有过滤器(如果存在)后使用'ToList()'方法进行查询。所以我的方法只会查询db一次。 –
真棒,在这里得到一些铸造的问题,但我研究,... VAR种族= ddlRace.SelectedItem.Value.TrimEnd(); photosquery = photosquery.Where(x => x.Race == race); iEnnumerable到GeneralList – dotNETEngineer