2017-10-14 105 views
0

我的查詢低於比較。有人可以幫助我如何在我的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(); 

回答

1

你可以重寫查詢以避免混合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(); 

注:我已經寫在記事本中,所以它可能有錯誤。不過,我希望的想法是明確

+0

困難的部分是將有大量的數據,並希望這是好的有沒有減慢加載時間我會盡力。謝謝。 – dotNETEngineer

+0

@dotNETEngineer當你第一次創建'usersquery'時沒有發生實際的數據獲取。數據將在應用所有過濾器(如果存在)後使用'ToList()'方法進行查詢。所以我的方法只會查詢db一次。 –

+0

真棒,在這裏得到一些鑄造的問題,但我研究,... VAR種族= ddlRace.SelectedItem.Value.TrimEnd(); photosquery = photosquery.Where(x => x.Race == race); iEnnumerable到GeneralList – dotNETEngineer

相關問題