Linq IQueryable method use with join method - c#

Here is my linq code with join - my first class is the main table (SKontrat), other class has a relation with the SKontrat class:
var result = from k in SKontrat()
join kk in SKontratKalem() on k.ID equals kk.UstID
join m in SKontratMasraflari() on k.ID equals m.KontratID
join s in SKontratSatisSekli() on k.ID equals s.KontratID
join tb in SKontratTarihBaglantilar() on k.ID equals tb.KontratID
join gp in SKontratGP() on k.ID equals gp.KontratID
select new
{
k.ID,
k.Tip,
k.KontratNo,
BagliOlduguEvrakNo = db.BagliOlduguKontratlarGetir(k.ID),
k.FirmaIsmi,
k.InspektorAdi,
k.PlasiyerAdi,
k.Not1,
k.Not2,
k.Not3,
k.DovizBirim,
Miktar = SKontratKalem().Sum(q => q.Miktar),
TahminiGenelToplam = db.SiparisRaporuTahminiGenelToplam(k.ID, Convert.ToInt32(kk.MusteriID), Convert.ToInt32(kk.TedarikciID)),
GercekGenelToplam = db.SiparisRaporuGercekGenelToplam(k.ID, Convert.ToInt32(kk.MusteriID), Convert.ToInt32(kk.TedarikciID)),
GpGercekKdvliTutar = db.GpGercekKdvliTutar(k.ID, Convert.ToDecimal(txtBrutToplamGelirGPKdvli1.Text), Convert.ToDecimal(txtBrutToplamGelirGPKdvli2.Text), txtBrutToplamGelirGPKdvsizBirim.Text),
GpTahminiKdvliTutar = db.GpTahminiKdvliTutar(k.ID, Convert.ToDecimal(txtBrutToplamGelirGPKdvli1.Text), Convert.ToDecimal(txtBrutToplamGelirGPKdvli2.Text), txtBrutToplamGelirGPKdvsizBirim.Text),
TarihBaglantiDurum = tb.TDosyaKapandi.Value.ToString() != "" || tb.TDosyaKapandi != null ? "Dosya Kapandı" : "Beklemede",
k.KayitTarihi,
k.MarkalamaTarihi,
k.TeslimSekli,
k.IrsaliyeSekli,
OperasyonTarihi = tb.Operasyonda,
DosyaKapandi = tb.TDosyaKapandi,
SevkiyatTarihi = tb.SevkiyatGerceklesen,
k.KayitYapanKullanici,
k.KayitTarihi_DB,
k.DuzenlemeYapanKullanici,
k.DuzenlemeTarihi_DB
};
grSonuclar.DataSource = result.ToList();
and here is the IQueryable class one of them:
private IQueryable<KontratUst> SKontrat()
{
var _result = PredicateBuilder.True<KontratUst>();
_result = _result.And(x => x.Tip == KontratTipi);
_result = _result.And(x => x.Silindi == 0);
if (txtFirmaIsmi.Text != string.Empty)
_result = _result.And(x => x.FirmaIsmi.Contains(txtFirmaIsmi.Text));
if (txtKayitTarihi1.Text != string.Empty && txtKayitTarihi2.Text != string.Empty)
_result = _result.And(x => x.KayitTarihi >= txtKayitTarihi1.DateTime && x.KayitTarihi <= txtKayitTarihi2.DateTime);
else if (txtKayitTarihi1.Text != string.Empty)
_result = _result.And(x => x.KayitTarihi >= txtKayitTarihi1.DateTime);
else if (txtKayitTarihi2.Text != string.Empty)
_result = _result.And(x => x.KayitTarihi <= txtKayitTarihi2.DateTime);
if (txtKayitTarihi1.Text != string.Empty && txtMarkalamaTarihi2.Text != string.Empty)
_result = _result.And(x => x.MarkalamaTarihi >= txtMarkalamaTarihi1.DateTime && x.MarkalamaTarihi <= txtMarkalamaTarihi2.DateTime);
else if (txtMarkalamaTarihi1.Text != string.Empty)
_result = _result.And(x => x.MarkalamaTarihi >= txtMarkalamaTarihi1.DateTime);
else if (txtMarkalamaTarihi2.Text != string.Empty)
_result = _result.And(x => x.MarkalamaTarihi <= txtMarkalamaTarihi2.DateTime);
if (txtContractTarihi1.Text != string.Empty && txtMarkalamaTarihi2.Text != string.Empty)
_result = _result.And(x => x.KontratTarihi >= txtContractTarihi1.DateTime && x.KontratTarihi <= txtContractTarihi2.DateTime);
else if (txtContractTarihi1.Text != string.Empty)
_result = _result.And(x => x.KontratTarihi >= txtContractTarihi1.DateTime);
else if (txtContractTarihi2.Text != string.Empty)
_result = _result.And(x => x.KontratTarihi <= txtContractTarihi2.DateTime);
if (txtPlasiyerAdi.Text != string.Empty)
_result = _result.And(x => x.PlasiyerAdi.Contains(txtPlasiyerAdi.Text));
if (txtYardimciPlasiyer.Text != string.Empty)
_result = _result.And(x => x.YardimciPlasiyerAdi.Contains(txtYardimciPlasiyer.Text));
if (txtYardimSekli.Text != string.Empty)
_result = _result.And(x => x.YardimSekli.Contains(txtYardimSekli.Text));
if (txtMusteriTemsilcisi.Text != string.Empty)
_result = _result.And(x => x.MusteriTemsilcisi.Contains(txtMusteriTemsilcisi.Text));
if (txtInspektorAdi.Text != string.Empty)
_result = _result.And(x => x.InspektorAdi.Contains(txtInspektorAdi.Text));
var _return = db.KontratUsts.Where(_result);
return _return;
}
and I am getting an error like this:
FormatException occurred: Input string was not in a correct format.

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.

LINQ using Contains with entity

Am using ASP.NET MVC 5 to create an Application for billing, now i have thing function which receive a filter object with different variables, am having a problem with contains when i search, what am i doing wrong
public static List<Quote> getCustomerQuotes(QuoteFilter filter)
{
using (var db = new AppDBContext())
{
var q = db.Quotes.Where(u => u.entryDate > 0); ;
if (filter.type != null)
{
q = q.Where(u => u.quoteType == filter.type);
}
if (filter.only_permitable != null)
{
q = q.Where(u => !Values.NON_PERMITABLE_QUOTES.Contains(u.quoteType));
}
if (filter.quote_status != null)
q = q.Where(u => u.quote_status == (int)filter.quote_status);
if (filter.quotenumber != null)
{
q = q.Where(u => u.quote_number.Contains(filter.quotenumber));
}
if (filter.permitnumber != null)
q = q.Where(u => u.permit_number.Contains(filter.permitnumber));
if (filter.permit_status != null)
q = q.Where(u => u.permit_status == (int)filter.permit_status);
if (filter.quoteId != null)
q = q.Where(u => u.Id == (int)filter.quoteId);
if (filter.customer_id != null)
q = q.Where(u => u.customer_id == (int)filter.customer_id);
q = q.OrderByDescending(u => u.Id);
FileLogger.Log("getCustomerQuotes", q.ToString());
return q.ToList();
}
}
When i call the function and pass quotenumber, the contains doesnt search, it returns nothing
You have to evaluate your expression, before you apply the OrderByDescending.
q = q.Where(u => u.quote_number.Contains(filter.quotenumber)).ToList();
This should be happen also to the rest places.
Is quote number alpha-numeric? If yes, as Contains is case sensitive can you try comparison by first turning source and target to same case ? like
q = q.Where(u => u.quote_number.ToLower().Contains(filter.quotenumber.ToLower()));
Cheers
Ok, am answering my own question after finding a solution or i may call it a hack
public static List<Quote> getCustomerQuotes(QuoteFilter filter)
{
using (var db = new AppDBContext())
{
var q = db.Quotes.Where(u =>
(filter.type != null ? u.quoteType == filter.type : u.quoteType > 0) &&
(filter.only_permitable != null ? !Values.NON_PERMITABLE_QUOTES.Contains(u.quoteType) : u.permitType > 0) &&
(filter.quote_status != null ? u.quote_status == filter.quote_status : u.quote_status > -100) &&
(!string.IsNullOrEmpty(filter.quotenumber) ? u.quote_number.Contains(filter.quotenumber) || u.groupName.Contains(filter.quotenumber) : u.quoteType > 0) &&
(!string.IsNullOrEmpty(filter.permitnumber) ? u.permit_number.Contains(filter.permitnumber) || u.groupName.Contains(filter.permitnumber) : u.quoteType > 0) &&
(filter.permit_status != null ? u.permit_status == filter.permit_status : u.quoteType > 0) &&
(filter.quoteId != null ? u.Id == filter.quoteId : u.Id > 0) &&
(filter.customer_id != null ? u.customer_id == filter.customer_id : u.customer_id > -1)
).OrderByDescending(u => u.Id);
//FileLogger.Log("getCustomerQuotes", q.ToString());
return q.ToList();
}
}
i dont know why it didn't work the first time but now it works.

randomize Select do not work

I wrote a code that's going to accidentally bring back row of data
I want to 5 row chosen randomly but do not work and return value
Everything was true, but the part that is related to the random return just do not work anymore
public List<tblInvoice> Admin_GetRowsSendProduct(string StartDate, string EndDate, int status = -1, bool Randomize = false)
{
LtSProductDataContext db = new LtSProductDataContext(BLLBase.BLLBase.ConnectionString);
IQueryable<tblInvoice> xxx = db.tblInvoices.Where(p => p.status == true);
DateTime _StartDate = DateTime.MinValue;
DateTime _EndDate = DateTime.MinValue;
if (xConvertor.ToString(StartDate) == "" || xConvertor.ToString(EndDate) == "")
{
if (string.IsNullOrEmpty(StartDate) == false)
_StartDate = BLLBase.xDateTime.DateXorshid2DateMiladi(StartDate.ToString());
if (string.IsNullOrEmpty(EndDate) == false)
{
_EndDate = BLLBase.xDateTime.DateXorshid2DateMiladi(EndDate.ToString());
if (_StartDate == _EndDate) { _EndDate = _StartDate.AddDays(1); }
}
xxx = xxx.Where(p =>
(p.status == true) &&
(_StartDate == DateTime.MinValue || p.Date >= _StartDate) && (_EndDate == DateTime.MinValue || p.Date <= _EndDate));
}
else if (xConvertor.ToString(StartDate) != "" && xConvertor.ToString(EndDate) != "")
{
_StartDate = BLLBase.xDateTime.DateXorshid2DateMiladi(StartDate.ToString());
_EndDate = BLLBase.xDateTime.DateXorshid2DateMiladi(EndDate.ToString());
xxx = xxx.Where(p => p.Date <= _EndDate && p.Date >= _StartDate && p.status == true && p.SendStatus == status);
}
xxx = xxx.Where(p => (status == -1 || p.SendStatus == status) && p.status == true).OrderByDescending(p => p.Date);
if (Randomize)
{
Random rnd = new Random();
xxx = xxx.OrderBy(x => rnd.Next());
//xxx = xxx.OrderBy(o => Guid.NewGuid());
xxx = xxx.Take(3);
return xxx.Where(p => (p.isPostalPayment == null || p.isPostalPayment == false)).ToList();
}
else
{
return xxx.Where(p => (p.isPostalPayment == null || p.isPostalPayment == false)).ToList();
}
//return xxx.Where(p => p.PaymentType != 4).ToList();
}
do not work this section:
xxx = xxx.OrderBy(x => rnd.Next());
or
xxx = xxx.OrderBy(o => Guid.NewGuid());
if (Randomize)
{
List<tblInvoice> _Result = db.tblInvoices.ToList();
var _Temp = xxx.Where(p => (p.isPostalPayment == null || p.isPostalPayment == false)).ToList();
_Result = _Temp.OrderBy(o => Guid.NewGuid()).Take(5).ToList();
return _Result;
}

Dynamic EF Where Clause raising ArgumentNullException

I'm trying to code a method that, in it's class given the values of some of the attributes, returns a filtered DbSet. The code, so far, is:
public IEnumerable<Pesquisa> Pesquisas {
get {
PrometheusDBContext db = new PrometheusDBContext();
var temp = db.Pesquisas;
if ((this.Filtro.Nome != null) && (this.Filtro.Nome.Trim() != ""))
{
temp = (temp.Where(p => SqlFunctions.PatIndex(this.Filtro.Nome, p.Nome) > 0) as DbSet<Pesquisa>);
}
if ((this.Filtro.CodTipoPesquisa != null) && (this.Filtro.CodTipoPesquisa.Trim() != ""))
{
temp = (temp.Where(p => p.CodTipoPesquisa == this.Filtro.CodTipoPesquisa.Trim()) as DbSet<Pesquisa>);
}
if ((this.Filtro.IDStatusPesquisa != null) && (this.Filtro.IDStatusPesquisa > 0))
{
temp = (temp.Where(p => p.IDStatusPesquisa == this.Filtro.IDStatusPesquisa) as DbSet<Pesquisa>);
}
if ((this.Filtro.DataCriacao_Inicial != null) && (this.Filtro.DataCriacao_Final != null))
{
temp = (temp.Where(p => (p.DataCriacao >= this.Filtro.DataCriacao_Inicial) && (p.DataCriacao <= this.Filtro.DataCriacao_Final)) as DbSet<Pesquisa>);
}
else
{
if (this.Filtro.DataCriacao_Inicial != null)
{
temp = (temp.Where(p => p.DataCriacao >= this.Filtro.DataCriacao_Inicial) as DbSet<Pesquisa>);
}
if (this.Filtro.DataCriacao_Final != null)
{
temp = (temp.Where(p => p.DataCriacao <= this.Filtro.DataCriacao_Final) as DbSet<Pesquisa>);
}
}
return temp
.Include(p => p.Usuario)
.Include(p => p.StatusPesquisa)
.Include(p => p.TipoPesquisa)
.Include(p => p.ModeloTermoAdesao)
.Include(p => p.Pacientes)
.ToList();
}
Problem is: everytime one of the attributes is filled with some value (i.e.: this.Filtro.Nome = "test" ), the ToList() raises an ArgumentNullExcpetion. Any ideas?
You shouldn't cast to DbSet at the end of each line.
Also, declare
IQueryable<Pesquisa> temp = db.Pesuisas;
// your code follows.
The reason behind it is that although you start with a DbSet, applying operators changes its type. Your dynamic cast returns null then.

Categories

Resources