ورود

View Full Version : سوال: شرط گزاری در Lambda Expression



morika
پنج شنبه 15 آبان 1393, 14:39 عصر
سلام
من یه کوئری دارم به این شکل
var model = db.Files.Where(x => x.FileType == fileType && x.PropertyType == propertyType && x.UserType == userType && x.BuildingArea >= minArea && x.BuildingArea <= maxArea) .Join(db.Addresses, x => x.Id, y => y.FileId, (x, y) => new { file = x, addrees = y }).Where(y => y.addrees.State == _state && y.addrees.City == _city && y.addrees.Region == _region)
.Join(db.Prices, x2 => x2.file.Id, z => z.FileId, (x2, z) => new { fileAddress = x2, price = z }).Where(z => z.price.MainPrice >= minPrice && z.price.MainPrice <= maxPrice)
.Select(t => new SearchViewModel
{
Id = t.fileAddress.file.Id,
BuildingArea = t.fileAddress.file.BuildingArea,
City = t.fileAddress.addrees.City,
Code = t.fileAddress.file.Code,
FileType = t.fileAddress.file.FileType,
InsertDate = t.fileAddress.file.InsertDate,
IsSold = t.fileAddress.file.IsSold,
MainPrice = t.price.MainPrice,
PropertyType = t.fileAddress.file.PropertyType,
Region = t.fileAddress.addrees.Region,
Features = t.fileAddress.file.Features
});
توی این کوئری بعض اوقات ممکنه پارامتر (region = همه مناطق) و پارامتر (userType = همه موارد) بشه. که در این صورت اصلا نباید این دو پارامتر در کوئری شرکت داده بشن. حالا جحوری میشه این کارو انجام داد. البته به غیر از اینکه 4 بار به طور مختلف کل کوئری از اول نوشته بشه.
ممنون

morika
پنج شنبه 15 آبان 1393, 16:50 عصر
خودم یه جورایی درستش کردم.
var model = db.Files.Where(x => x.FileType == fileType && x.PropertyType == propertyType && x.BuildingArea >= minArea && x.BuildingArea <= maxArea) .Join(db.Addresses, x => x.Id, y => y.FileId, (x, y) => new { file = x, addrees = y }).Where(y => y.addrees.State == _state && y.addrees.City == _city)
.Join(db.Prices, x2 => x2.file.Id, z => z.FileId, (x2, z) => new { fileAddress = x2, price = z }).Where(z => z.price.MainPrice >= minPrice && z.price.MainPrice <= maxPrice);




if (userType != "")
{
model = model.Where(x => x.fileAddress.file.UserType == userType);
}


if (region > 0)
{
string _region = db.Regions.Find(region).Name;
model = model.Where(x => x.fileAddress.addrees.Region == _region);
}


ViewBag.facility = facility;
return View("List", model.Select(t => new SearchViewModel
{
Id = t.fileAddress.file.Id,
BuildingArea = t.fileAddress.file.BuildingArea,
City = t.fileAddress.addrees.City,
Code = t.fileAddress.file.Code,
FileType = t.fileAddress.file.FileType,
InsertDate = t.fileAddress.file.InsertDate,
IsSold = t.fileAddress.file.IsSold,
MainPrice = t.price.MainPrice,
PropertyType = t.fileAddress.file.PropertyType,
Region = t.fileAddress.addrees.Region,
Features = t.fileAddress.file.Features
}));