我的查询如下。有人可以帮我如何在 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();
您可以重写查询以避免将 linq 与 SQL 混合(并使其免受 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();
注意:我已经在记事本中写了它,所以它可能有错误。但是我希望想法很清楚