C# search by many parameters Entity Framework 6.0 - c#

In my table I have 4 columns: BAZAR_TEXT, CATEGORY, COUNTY, PRICE and I would like to search records by parameters from textboxes: search, category, county, priceFrom, priceUntil
var searchResult = db.bazar.Include(c => c.images).Where(da => da.BAZAR_TEXT.Contains(search) || search == null);
var categoryResult = searchResult.Where(x => x.CATEGORY == category || category == null);
var countyResult = categoryResult.Where(x => x.DISTRICT == county || county == null);
var priceFromResult = countyResult.Where(x => x.PRICE >= priceFrom);
var priceUntilResult = priceFromResult.Where(x => x.PRICE <= priceUntil);
return View(priceUntilResult.ToList().ToPagedList(page ?? 1, 10));
and need to return list to view.
If I search only by searchResults all is OK
var searchResult = db.bazar.Include(c => c.images).Where(da => da.BAZAR_TEXT.Contains(search) || search == null);
return View(searchResult.ToList().ToPagedList(page ?? 1, 10));
but If I add other results list is null.
Note: all parameters from textboxes can be null, but columns in table are not null.

var searchResult = db.bazar.Include(c => c.images).AsQueryable();
if(search != null){
searchResult = searchResult.Where(da => da.BAZAR_TEXT.Contains(search));
}
if(category != null){
searchResult = searchResult.Where(x => x.CATEGORY == category);
}
if(county != null){
searchResult = searchResult.Where(x => x.DISTRICT == county);
}
if(priceFrom != null){
searchResult = searchResult.Where(x => x.PRICE == priceFrom);
}
if(priceUntil != null){
searchResult = searchResult.Where(x => x.PRICE <= priceUntil);
}
return View(searchResult.ToList().ToPagedList(page ?? 1, 10));

There is difference between null and string empty. So if you search with empty textbox:
WebEntities db = new WebEntities();
var searchResult = db.bazar.Include(c => c.images);
if (!string.IsNullOrEmpty(search))
{
searchResult = searchResult.Where(da => da.BAZAR_TEXT.Contains(search));
}
if (!string.IsNullOrEmpty(category))
{
searchResult = searchResult.Where(x => x.CATEGORY == category);
}
if (!string.IsNullOrEmpty(county))
{
searchResult = searchResult.Where(x => x.DISTRICT == county);
}
if (priceFrom != null)
{
searchResult = searchResult.Where(x => x.PRICE >= priceFrom);
}
if (priceUntil != null)
{
searchResult = searchResult.Where(x => x.PRICE <= priceUntil);
}
return View(searchResult.ToList().ToPagedList(page ?? 1, 10));

You should reverse the order of condition evaluation
.Where(x => x.CATEGORY == category || category == null)
to
.Where(x => category == null || x.CATEGORY == category )

Related

How can I divide large list into smaller lists, e.g., containing 1000 elements each and call methods on the new list count times?

I have a method it has large size list and doing some business for each element. And it takes too long.
So I want to divide this list into smaller list. For example if I have 100.000 elements I have divide this list into 100 sub list that contains 1000 elements on each and I want to call my method one time but it should 100 times on time , I think for this I need threads. Is there any solution for my request? Thank you.
Here is my code :
private void TransferOrderDetails()
{
using (var context = new BbsfDbContext())
{
context.DisableFilter(AbpDataFilters.MayHaveTenant);
context.DisableFilter("LanguageSpecificFilter");
List<SapOrderDetail> sapOrderDetails = new List<SapOrderDetail>();
List<OrderDetailView> orderDetails = new List<OrderDetailView>();
using (new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }))
{
//In here I have 100.000 or above records it takes 2 hours finish this method
sapOrderDetails = context.SapOrderDetails
.Where(p => p.IsRead == false)
.Where(p => !context.Orders.Select(a => a.Quote.SapCode).Contains(p.VBELN))
.Where(p => context.Orders.Any(o => o.SapCode == p.VBELN)
&& context.ProductionSites.Any(a => a.SapCode == p.WERKS))
.OrderBy(p => p.CreatedDate)
.ToList();
//orderDetails = context.OrderDetailView.ToList();
}
//ListExtensions.ChunkBy(sapOrderDetails, 1000);
if (!sapOrderDetails.Any()) return;
var productionSites = context.ProductionSites.AsNoTracking().ToList();
var productGroups = context.ProductGroups.Include(a => a.ParentGroup).Select(p => new { p.Id, p.ParentGroup }).AsNoTracking().ToList();
var contractDetails = context.ContractDetails.AsNoTracking().ToList();
var materialGroups = context.MaterialGroups.AsNoTracking().ToList();
var rejectionReasons = context.RejectionReasons.AsNoTracking().ToList();
var currencyDefinitions = context.CurrencyDefinitions.AsNoTracking().ToList();
var measurementUnits = context.MeasurementUnits.AsNoTracking().ToList();
var salesDepots = context.SalesDepots.AsNoTracking().ToList();
var shipmentPoints = context.ShipmentPoints.AsNoTracking().ToList();
var stockStatusTypes = context.StockStatusTypes.ToList();
var user = context.Users.FirstOrDefault(u => u.UserName == AbpUserBase.AdminUserName);
var counter = 0;
foreach (var item in sapOrderDetails)
{
counter++;
try
{
Order order = null;
OrderDetail orderDetail = null;
var detail = context.OrderDetails
.Include(a => a.Order)
.FirstOrDefault(a => a.Order.SapCode == item.VBELN && a.SapCode == item.POSNR);
if (detail != null)
{
order = detail.Order;
orderDetail = detail;
}
if (order == null)
{
order = context.Orders.FirstOrDefault(p => p.SapCode == item.VBELN);
if (order == null)
continue;
}
var productionSite = context.ProductionSites.FirstOrDefault(p => p.SapCode == item.WERKS);
if (productionSite == null)
continue;
var product = context.Products.Include("ProductGroup").FirstOrDefault(p => p.SapCode == item.MATNR && p.ProductionSite.Id == productionSite.Id);
if (product == null)
continue;
var stockStatus = stockStatusTypes.FirstOrDefault(s => s.Id == product.GeneralStockStatusId);
var contractDetail = contractDetails.FirstOrDefault(p => p.ContractSapCode == item.VGBEL && p.SapCode == item.VGPOS);
if (orderDetail == null)
{
orderDetail = context.OrderDetails.FirstOrDefault(p => p.OrderId == order.Id && p.SapCode == item.POSNR);
}
if (product.ProductGroup != null)
{
var productGroup3 = context.ProductGroups.Include("ParentGroup").FirstOrDefault(p => p.Id == product.ProductGroup.Id);
if (productGroup3 != null && productGroup3.ParentGroup != null)
{
var productGroup2 = context.ProductGroups.Include("ParentGroup").FirstOrDefault(p => p.Id == productGroup3.ParentGroup.Id);
if (productGroup2 != null && productGroup2.ParentGroup != null)
{
var productGroup1 = context.ProductGroups.Include("ParentGroup").FirstOrDefault(p => p.Id == productGroup2.ParentGroup.Id);
if (productGroup1 != null && productGroup1.ParentGroup != null)
order.ProductGroup = productGroup1.ParentGroup;
}
}
}
if (orderDetail == null)
{
orderDetail = new OrderDetail
{
Order = order,
SapCode = item.POSNR,
Product = product,
MaterialGroup = materialGroups.FirstOrDefault(p => p.SapCode == item.MATKL),
RejectionReason = rejectionReasons.FirstOrDefault(p => p.SapCode == item.ABGRU),
BaseAmount = item.NETWR,
Currency = currencyDefinitions.FirstOrDefault(p => p.SapCode == item.WAERK),
OrderAmount = item.KWMENG,
MeasurementUnit = measurementUnits.FirstOrDefault(p => p.IsoCode == item.VRKME),
GrossWeight = item.BRGEW,
NetWeight = item.NTGEW,
WeightUnit = measurementUnits.FirstOrDefault(p => p.IsoCode == item.GEWEI),
ContractSapCode = item.VGBEL,
ContractDetailSapCode = item.VGPOS,
ContractName = contractDetail?.Name,
//ProductionSite = productionSite,
SalesDepot = salesDepots.FirstOrDefault(p => p.SapCode == item.LGORT),
ShipmentPoint = shipmentPoints.FirstOrDefault(p => p.SapCode == item.VSTEL),
NetPrice = item.NETPR,
//PEINH
//PMENE
//VGTYP
Tax = item.MWSBP,
//PRSDT
RequestedAmount = item.KWMENG,
RequestedDeliveryDate = item.ZZMITT,
CreationTime = DateTime.Now,
LastModificationTime = DateTime.Now,
CreatorUserId = user.Id,
LastModifierUserId = user.Id,
IsDueDateRequested = item.ZZPRODDATE.HasValue,
DueDate = (string.IsNullOrEmpty(item.MVGR3) && item.ZZPRODDATE.HasValue) ? DateTime.Now : item.ZZPRODDATE,
DeliveryStatus = item.ZZPRODDATE.HasValue ? OrderDetailDeliveryStatus.FulfilledDueDate : OrderDetailDeliveryStatus.Approved,
StockStatus = stockStatus,
Note = item.MusteriNotu,
Uepos = item.UEPOS,
Type = item.PSTYV,
DOCNUM = item.DOCNUM,
ProductParty = item.CHARG
};
orderDetail.ProductionSiteId = productionSite?.Id;
if (orderDetail.RejectionReason != null || orderDetail.RejectionReasonId != null)
{
orderDetail.Status = OrderDetailStatus.Canceled;
orderDetail.DeliveryStatus = OrderDetailDeliveryStatus.Canceled;
}
if (string.IsNullOrEmpty(item.MVGR3) && item.ZZPRODDATE.HasValue)
orderDetail.DueDate = DateTime.Now;
else
orderDetail.DueDate = item.ZZPRODDATE;
context.OrderDetails.Add(orderDetail);
}
else
{
orderDetail.Product = product;
orderDetail.MaterialGroup = materialGroups.FirstOrDefault(p => p.SapCode == item.MATKL);
orderDetail.RejectionReason = rejectionReasons.FirstOrDefault(p => p.SapCode == item.ABGRU);
orderDetail.BaseAmount = item.NETWR;
orderDetail.Currency = currencyDefinitions.FirstOrDefault(p => p.SapCode == item.WAERK);
orderDetail.OrderAmount = item.KWMENG;
orderDetail.MeasurementUnit = measurementUnits.FirstOrDefault(p => p.IsoCode == item.VRKME);
orderDetail.GrossWeight = item.BRGEW;
orderDetail.NetWeight = item.NTGEW;
orderDetail.WeightUnit = measurementUnits.FirstOrDefault(p => p.IsoCode == item.GEWEI);
orderDetail.ContractSapCode = item.VGBEL;
orderDetail.ContractDetailSapCode = item.VGPOS;
//orderDetail.ProductionSite = productionSite;
orderDetail.SalesDepot = salesDepots.FirstOrDefault(p => p.SapCode == item.LGORT);
orderDetail.ShipmentPoint = shipmentPoints.FirstOrDefault(p => p.SapCode == item.VSTEL);
orderDetail.NetPrice = item.NETPR;
//PEINH
//PMENE
//VGTYP
orderDetail.Tax = item.MWSBP;
//PRSDT
//orderDetail.RequestedAmount = orderDetail.RequestedAmount.HasValue ? orderDetail.RequestedAmount : item.KWMENG;
orderDetail.RequestedDeliveryDate = orderDetail.RequestedDeliveryDate.HasValue ? orderDetail.RequestedDeliveryDate : item.ZZMITT;
orderDetail.LastModifierUserId = user.Id;
orderDetail.LastModificationTime = DateTime.Now;
orderDetail.DueDate = (string.IsNullOrEmpty(item.MVGR3) && item.ZZPRODDATE.HasValue) ? DateTime.Now : item.ZZPRODDATE;
//orderDetail.IsDueDateRequested = item.ZZPRODDATE.HasValue;
orderDetail.Note = item.MusteriNotu;
orderDetail.Uepos = item.UEPOS;
orderDetail.Type = item.PSTYV;
orderDetail.DOCNUM = item.DOCNUM;
orderDetail.ProductParty = item.CHARG;
if (contractDetail != null && !string.IsNullOrEmpty(contractDetail.Name))
orderDetail.ContractName = contractDetail.Name;
//todo delivery statusleri sil
//termın ıstenmısse statusu termın verıldı olmalı
if (!orderDetail.DeliveryStatus.HasValue && orderDetail.IsDueDateRequested)
orderDetail.DeliveryStatus = OrderDetailDeliveryStatus.AwaitingDueDate;
//durumu termin bekliyor olan kaleme termin verildiğinde statusu termın verıldı olmalı
if ((!orderDetail.DeliveryStatus.HasValue || orderDetail.DeliveryStatus == OrderDetailDeliveryStatus.AwaitingDueDate) && orderDetail.DueDate.HasValue)
orderDetail.DeliveryStatus = OrderDetailDeliveryStatus.FulfilledDueDate;
orderDetail.ProductionSiteId = productionSite?.Id;
if ((orderDetail.RejectionReason != null || orderDetail.RejectionReasonId != null) && item.ABGRU != null)
{
orderDetail.Status = OrderDetailStatus.Canceled;
}
if (item.ABGRU == null)
{
orderDetail.Status = OrderDetailStatus.Open;
orderDetail.RejectionReasonId = null;
if (!orderDetail.DeliveryStatus.HasValue && orderDetail.IsDueDateRequested)
orderDetail.DeliveryStatus = OrderDetailDeliveryStatus.AwaitingDueDate;
else if ((!orderDetail.DeliveryStatus.HasValue || orderDetail.DeliveryStatus == OrderDetailDeliveryStatus.AwaitingDueDate) && orderDetail.DueDate.HasValue)
orderDetail.DeliveryStatus = OrderDetailDeliveryStatus.FulfilledDueDate;
else
orderDetail.DeliveryStatus = OrderDetailDeliveryStatus.Canceled;
}
if (string.IsNullOrEmpty(item.MVGR3) && item.ZZPRODDATE.HasValue)
orderDetail.DueDate = DateTime.Now;
else
orderDetail.DueDate = item.ZZPRODDATE;
}
item.IsRead = true;
item.ModifiedDate = DateTime.Now;
}
catch (Exception ex)
{
logger.Error(ex, MethodBase.GetCurrentMethod().Name + " Error During IDOCOperations " + ex.Message);
continue;
}
}
try
{
context.BulkSaveChanges(false);
}
catch (Exception ex)
{
logger.Error(ex, MethodBase.GetCurrentMethod().Name + " Error During IDOCOperations " + ex.Message);
}
}
}

The cast to value type System.Boolean failed because the materialized value is null, result type's generic parameter must use a nullable type

This code was working before but now I've got this error: The cast to value type 'System.Boolean' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
public async Task<ActionResult> BankDepositVoucher(BankDepositVoucherSearchViewModel search, int? PageNo)
{
var model = new BankDepositVoucherListViewModel
{
Search = search ?? new BankDepositVoucherSearchViewModel()
};
if (search != null)
{
search.StartDate = search.StartDate.ToStartOfDay();
search.EndDate = search.EndDate.ToEndOfDay();
}
try
{
var Vouchers = DbManager.Invoices.Include(x => x.BankDepositVoucher)
.Where(x => x.Type == InvoiceType.BankDepositVoucher
&& (x.VoucherNumber == search.VoucherNo || search.VoucherNo == null)
&& (x.BankDepositVoucher.SlipNo.Contains(search.SlipNo) || search.SlipNo == null)
&& (x.BankDepositVoucher.ChequeNo.Contains(search.ChequeNo) || search.ChequeNo == null)
&& (x.BankDepositVoucher.Bank.AccountName.Contains(search.BankDetails)
|| search.BankDetails == null)
&& (x.BankDepositVoucher.AccountName.Contains(search.AccountName) || search.AccountName == null)
&& (x.BankDepositVoucher.Narration.Contains(search.Narration) || search.Narration == null)
&& (x.TotalAmount == search.Amount || search.Amount == null)
&& (x.Date >= search.StartDate || search.StartDate == null)
&& (x.Date <= search.EndDate || search.EndDate == null));
//model.Pager = new Pager(await Vouchers.CountAsync(), PageNo, 10);
model.Vouchers = await Vouchers.OrderByDescending(x => x.VoucherNumber)
//.Skip((model.Pager.CurrentPage - 1) * model.Pager.PageSize)
//.Take(model.Pager.PageSize)
.Select(x => new BankDepositVoucherBaseViewModel
{
Id = x.Id,
VoucherNumber = x.VoucherNumber,
AccountName = x.BankDepositVoucher.AccountName,
BankAccountName = x.BankDepositVoucher.Bank.AccountName,
Date = x.Date,
ChequeNo = x.BankDepositVoucher.ChequeNo,
Narration = x.BankDepositVoucher.Narration,
SlipNo = x.BankDepositVoucher.SlipNo,
TotalAmount = x.TotalAmount,
IsCleared = x.BankDepositVoucher.IsCleared
}).ToListAsync();
}
catch (Exception ex)
{
Console.WriteLine("", ex.Message);
}
return PartialView(model);
}
This is the part throwing above mentioned exception
model.Vouchers = await Vouchers.OrderByDescending(x => x.VoucherNumber)
//.Skip((model.Pager.CurrentPage - 1) * model.Pager.PageSize)
//.Take(model.Pager.PageSize)
.Select(x => new BankDepositVoucherBaseViewModel
{
Id = x.Id,
VoucherNumber = x.VoucherNumber,
AccountName = x.BankDepositVoucher.AccountName,
BankAccountName = x.BankDepositVoucher.Bank.AccountName,
Date = x.Date,
ChequeNo = x.BankDepositVoucher.ChequeNo,
Narration = x.BankDepositVoucher.Narration,
SlipNo = x.BankDepositVoucher.SlipNo,
TotalAmount = x.TotalAmount,
IsCleared = x.BankDepositVoucher.IsCleared
}).ToListAsync();
The issue is likely that when populating the view model it cannot deal with the fact that a record may not have a BankDepositVoucher.
For instance:
IsCleared = x.BankDepositVoucher.IsCleared
This should probably be:
IsCleared = x.BankDepositVoucher?.IsCleared ?? false
One other thing to improve performance considerably:
While it may look concise in the code to write statements like this:
.Where(x => x.Type == InvoiceType.BankDepositVoucher
&& (x.VoucherNumber == search.VoucherNo || search.VoucherNo == null)
&& (x.BankDepositVoucher.SlipNo.Contains(search.SlipNo) || search.SlipNo == null)
&& (x.BankDepositVoucher.ChequeNo.Contains(search.ChequeNo) || search.ChequeNo == null)
&& (x.BankDepositVoucher.Bank.AccountName.Contains(search.BankDetails)
|| search.BankDetails == null)
&& (x.BankDepositVoucher.AccountName.Contains(search.AccountName) || search.AccountName == null)
&& (x.BankDepositVoucher.Narration.Contains(search.Narration) || search.Narration == null)
&& (x.TotalAmount == search.Amount || search.Amount == null)
&& (x.Date >= search.StartDate || search.StartDate == null)
&& (x.Date <= search.EndDate || search.EndDate == null));
It is more efficient to write it out as:
.Where(x => x.Type == InvoiceType.BankDepositVoucher);
if(!string.IsNullOrEmpty(search.VoucherNo))
Voucher = Voucher.Where(x => x.VoucherNumber == search.VoucherNo);
if(!string.IsNullOrEmpty(search.SlipNo))
Voucher = Voucher.Where(x => x.BankDepositVoucher.SlipNo.Contains(search.SlipNo))
// etc.
The reason is that in the first case you are generating a much larger SQL statement to be sent to the database, and it is quite easy to "slip up" on conditions if that query is ever edited in the future. (missing parenthesis, etc.) The second example only adds conditions to the query if they are needed, keeping the resulting SQL statement much more compact.

Using AND in JOIN in LINQ

I have such a SQL:
SELECT Items.ItemCode AS code, Items.ItemName AS name, ISNULL(PLID.PriceOverule,Items.ItemPrice) AS price from tblPLItemsDetail PLID
INNER JOIN tblItems Items ON PLID.ItemID = Items.ItemID
AND Items.ValidityTo IS NULL
WHERE PLItemID = #PLItemID
AND PLID.ValidityTo IS NULL
AND (PLID.ValidityFrom >= #LastUpdated OR #LastUpdated IS NULL)
I put this on LINQ:
details = context.TblPlitemsDetail
.Join(imisContext.TblItems,
p => p.ItemId,
i => i.ItemId,
(p, i) => new { TblPlitemsDetail = p, TblItems = i })
.Where(r => r.TblPlitemsDetail.PlitemId == PLItemID
&& r.TblPlitemsDetail.ValidityTo == null
&& (r.TblPlitemsDetail.ValidityFrom >= Convert.ToDateTime(model.last_update_date) || model.last_update_date == null))
.Select(x => new CodeNamePrice()
{
code = x.TblItems.ItemCode,
name = x.TblItems.ItemName,
price = (x.TblPlitemsDetail.PriceOverule == null) ? x.TblItems.ItemPrice.ToString() : x.TblPlitemsDetail.PriceOverule.ToString()
}).ToList();
I've rewritten most of the code but I have not implemented the AND Items.ValidityTo IS NULL predicate in the JOIN.
How to do it correctly?
As it is an INNER JOIN you can specify the extra predicate (Items.ValidityTo IS NULL) in a LINQ Where clause:
details = context.TblPlitemsDetail
.Join(imisContext.TblItems, p => p.ItemId, i => i.ItemId, (p, i) => new { TblPlitemsDetail = p, TblItems = i })
.Where(r => !r.TblItems.ValidityTo.HasValue)
.Where(r => r.TblPlitemsDetail.PlitemId == PLItemID && r.TblPlitemsDetail.ValidityTo == null && (r.TblPlitemsDetail.ValidityFrom >= Convert.ToDateTime(model.last_update_date) || model.last_update_date == null))
.Select(x => new CodeNamePrice() { code = x.TblItems.ItemCode, name = x.TblItems.ItemName, price = (x.TblPlitemsDetail.PriceOverule == null) ? x.TblItems.ItemPrice.ToString() : x.TblPlitemsDetail.PriceOverule.ToString() }).ToList();

Entity Framework querying error

Why does this work:
List<Item> items = ndb.Items.Where(m => m.ProductId == id).OrderByDescending(m => m.Id).ToList();
int itemid = items[0].Id;
bool wlexists = ndb.Wishlists.Any(m => m.ItemId == itemid && m.UserEmail == User.Identity.Name);
And this doesn't :
List<Item> items = ndb.Items.Where(m => m.ProductId == id).OrderByDescending(m => m.Id).ToList();
bool wlexists = ndb.Wishlists.Any(m => m.ItemId == items[0].Id && m.UserEmail == User.Identity.Name);
It must work if the items had value i.e not null . What error you are getting???
Do like this.
List<Item> items = ndb.Items.Where(m => m.ProductId == id).OrderByDescending(m => m.Id).ToList();
if(items!=null)
bool wlexists = ndb.Wishlists.Any(m => m.ItemId == items[0].Id && m.UserEmail == User.Identity.Name);

how to simplify if else using entity framework

how to simplify below code:
public List<Cwzz_CashFlowItem> AllDataPage(int start, int limit, out int total, string xmbmLike, string xmmcLike)
{
List<Cwzz_CashFlowItem> ll;
if (xmbmLike != "" && xmmcLike != "")
{
total = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowCode.Contains(xmbmLike))
.Count(v => v.CashFlowName.Contains(xmmcLike));
ll = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowCode.Contains(xmbmLike))
.Where(v => v.CashFlowName.Contains(xmmcLike))
.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit).ToList();
}
else if (xmbmLike != "" && xmmcLike == "")
{
total = _ctx.Cwzz_CashFlowItem
.Count(v => v.CashFlowCode.Contains(xmbmLike));
ll = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowCode.Contains(xmbmLike))
.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit).ToList();
}
else if (xmbmLike == "" && xmmcLike != "")
{
total = _ctx.Cwzz_CashFlowItem
.Count(v => v.CashFlowName.Contains(xmmcLike));
ll = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowName.Contains(xmmcLike))
.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit).ToList();
}
else
{
total = _ctx.Cwzz_CashFlowItem.Count();
ll = _ctx.Cwzz_CashFlowItem
.OrderBy(v => v.CashFlowCode)
.Skip(start).Take(limit).ToList();
}
return ll;
}
if there are more conditions not two, the if-else will be more complicated, so how to simplify code above.
Linq expressions can be chained. Avoid premature coercion into a List<>.
public IQueryable<Cwzz_CashFlowItem> AllDataPage(...) {
IQueryable<Cwzz_CashFlowItem> ll = _ctx.Cwzz_CashFlowItem;
if (xmbmLike != "")
{
ll = ll.Where(v => v.CashFlowCode.Contains(xmbmLike));
}
if (xmcmLike != "")
{
ll = ll.Where(v => v.CashFlowCode.Contains(xmcmLike));
}
return ll.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit);
}
I'll leave returning the out Count as an exercise.

Categories

Resources