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;
}
Related
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);
}
}
}
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.
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.
I have following method that registers a contact in database, but before register I check the contact exists or not:
bool RegisterContact(Contact contactInfo) {
bool entityExists =
_dbContext.Contacts.FirstOrDefault(
p => (p.FilesID.Equals(contactInfo.FilesID))
&& (p.EmailAddress ==
(string.IsNullOrEmpty(
contactInfo.EmailAddress)
? p.EmailAddress
: contactInfo.EmailAddress))
&&
(p.DisplayName ==
(string.IsNullOrEmpty(
contactInfo.DisplayName)
? p.DisplayName
: contactInfo.DisplayName)));
}
this query includes the fields that contain value (not null) in search condition (FilesID, EmailAddress, DisplayName)
this technique works fine in MSSQL, today i changed the database manager to PostgreSQL and use Npgsql.
All things work except above linq query, which raises an exception with message of : "could not determine data type of parameter $2"
I was forced to solve it in this way:
bool RegisterContact(Contact contactInfo)
{
Contact entityExists = null;
if (string.IsNullOrEmpty(contactInfo.EmailAddress) &&
(string.IsNullOrEmpty(contactInfo.DisplayName)))
entityExists =
_dbContext.Contacts.FirstOrDefault(
p => p.FilesID.Equals(contactInfo.FilesID));
if (!string.IsNullOrEmpty(contactInfo.EmailAddress) && string.IsNullOrEmpty(contactInfo.DisplayName))
entityExists =
_dbContext.Contacts.FirstOrDefault(
p =>
p.FilesID.Equals(contactInfo.FilesID) &&
p.EmailAddress == contactInfo.EmailAddress);
if (string.IsNullOrEmpty(contactInfo.EmailAddress) && !string.IsNullOrEmpty(contactInfo.DisplayName))
entityExists =
_dbContext.Contacts.FirstOrDefault(
p =>
p.FilesID.Equals(contactInfo.FilesID) &&
p.DisplayName == contactInfo.DisplayName);
if (!string.IsNullOrEmpty(contactInfo.EmailAddress) &&
!string.IsNullOrEmpty(contactInfo.DisplayName))
entityExists =
_dbContext.Contacts.FirstOrDefault(
p =>
p.FilesID.Equals(contactInfo.FilesID) &&
p.EmailAddress == contactInfo.EmailAddress &&
p.DisplayName == contactInfo.DisplayName);
}
Is this Npgsql bug or by design? any known solutions/workarounds for the problem?
I currently have the same cases. I think the problem is the lack of recognition, by NpgSQL, of string.IsNullOrEmpty.
I replaced the test with a check on empty string, always recognizing as not NULL the input parameter.
-- bad
var data = from art in _ctx.Set<Soleo.Model.DLAR>()
from iva in _ctx.Set<Soleo.Model.DLAI>().Where(k => k.DITTA == art.DITTA && k.COD == art.CIVA).DefaultIfEmpty()
from fam in _ctx.Set<Soleo.Model.DLFA>().Where(k => k.DITTA == art.DITTA && k.COD == art.FAM).DefaultIfEmpty()
from mar in _ctx.Set<Soleo.Model.DLMA>().Where(k => k.DITTA == art.DITTA && k.COD == art.MAR).DefaultIfEmpty()
from udm in _ctx.Set<Soleo.Model.DLUM>().Where(k => k.DITTA == art.DITTA && k.COD == art.UM).DefaultIfEmpty()
where art.DITTA == DLAUTH.Config.Current.DITTA && art.COD.Contains(sel_cod) && art.DES.Contains(sel_des)
&& (string.IsNullOrEmpty(sel_fam) || string.Compare(art.FAM, sel_fam, true) == 0)
&& (string.IsNullOrEmpty(sel_mar) || string.Compare(art.MAR, sel_mar, true) == 0)
&& (art.DIS >= sel_dis_da && art.DIS <= sel_dis_a)
select new
{
COD = art.COD,
DES = art.DES,
DES_UDM = udm.DES,
DES_MAR = mar.DES,
DES_FAM = fam.DES,
DES_CIVA = iva.DES,
MAG1 = art.MAG1,
MAG2 = art.MAG2,
DES_DIS = art.DIS == 1 ? "Si" : "No"
};
-- good:
var data = from art in _ctx.Set<Soleo.Model.DLAR>()
from iva in _ctx.Set<Soleo.Model.DLAI>().Where(k => k.DITTA == art.DITTA && k.COD == art.CIVA).DefaultIfEmpty()
from fam in _ctx.Set<Soleo.Model.DLFA>().Where(k => k.DITTA == art.DITTA && k.COD == art.FAM).DefaultIfEmpty()
from mar in _ctx.Set<Soleo.Model.DLMA>().Where(k => k.DITTA == art.DITTA && k.COD == art.MAR).DefaultIfEmpty()
from udm in _ctx.Set<Soleo.Model.DLUM>().Where(k => k.DITTA == art.DITTA && k.COD == art.UM).DefaultIfEmpty()
where art.DITTA == DLAUTH.Config.Current.DITTA && art.COD.Contains(sel_cod) && art.DES.Contains(sel_des)
&& (string.Compare(sel_fam, "", true) == 0 || string.Compare(art.FAM, sel_fam, true) == 0)
&& (string.Compare(sel_mar, "", true) == 0 || string.Compare(art.MAR, sel_mar, true) == 0)
&& (art.DIS >= sel_dis_da && art.DIS <= sel_dis_a)
select new
{
COD = art.COD,
DES = art.DES,
DES_UDM = udm.DES,
DES_MAR = mar.DES,
DES_FAM = fam.DES,
DES_CIVA = iva.DES,
MAG1 = art.MAG1,
MAG2 = art.MAG2,
DES_DIS = art.DIS == 1 ? "Si" : "No"
};
But I do not think this is the solution. I will report the case to NpgSQL.
I am developing an ASP.NET MVC 3 application using C# and Razor.
I have a search form that looks like this:
The search form works in the following way:
The user selects which property they want to search on.
The user selects how they want to match the search string (e.g. contains, starts with, ends with, equals, etc).
The user enters a search term and clicks Search.
The selections in the first drop down related directly to a property in my ADO.NET Entity Framework model class (and therefore directly to a table column).
Users need the ability to explicitly select which property and which matching method when searching, e.g. a user will explicitly search for all matches of process number that equals '132'.
My first approach was to use dynamic linq to construct a Where clause from the search criteria (see my original question). However I'm starting to think that this isn't the best way to do it.
I'm also hoping for a solution that doesn't require me to hard code the result for each property + matching criteria combination.
Any suggestions on how I should implement this search? It doesn't have to be using my current search form, totally open to any other ideas that fit the requirements.
Have you looked into using Lucene.NET for this project? given the nature of your searches it would be very simple to build that using Lucene, as it allows you to combine filters on different columns just like your requirements
You can build expression tree for where predicate using code. For example,
public static IQueryable<T> DynamicWhere<T>(this IQueryable<T> src, string propertyName, string value)
{
var pe = Expression.Parameter(typeof(T), "t");
var left = Expression.Property(pe, typeof(T).GetProperty(propertyName));
var right = Expression.Constant(value);
// Illustrated a equality condition but you can put a switch based on some parameter
// to have different operators
var condition = Expression.Equal(left, right);
var predicate = Expression.Lambda<Func<T, bool>>(condition, pe);
return src.Where(predicate);
}
Use it as Orders.DynamicWhere(searchBy, searchValue). You can add one more parameter to accept the operator such as Equals, Greater Than etc to complete the function.
See these links for more info:
http://msdn.microsoft.com/en-us/library/bb882637.aspx
http://msdn.microsoft.com/en-us/library/bb397951.aspx
Also check list of methods on the Expression class to get an idea.
You can use Dynamic Linq and you can create the Where clausole with a utility class like this:
public class Criteria
{
StringBuilder sb = new StringBuilder();
bool first = true;
public void And(string property, string dbOperator, string value) {
if (first)
{
sb.Append(" ").Append(property).Append(" ");
sb.Append(" ").Append(dbOperator).Append(" ");
sb.Append(" ").Append(value).Append(" ");
first = false;
}
else
{
sb.Append(" && ").Append(property).Append(" ");
sb.Append(" ").Append(dbOperator).Append(" ");
sb.Append(" ").Append(value).Append(" ");
}
}
public void Or(string property, string dbOperator, string value)
{
if (first)
{
sb.Append(" ").Append(property).Append(" ");
sb.Append(" ").Append(dbOperator).Append(" ");
sb.Append(" ").Append(value).Append(" ");
first = false;
}
else
{
sb.Append(" || ").Append(property).Append(" ");
sb.Append(" ").Append(dbOperator).Append(" ");
sb.Append(" ").Append(value).Append(" ");
}
}
public string ToString()
{
return sb.ToString();
}
}
So you can build a Criteria with many properties using Or or And methods and put it in the Where operator of Dynamic Linq.
We started out resolving similar queries against our Entity Framework model using dynamic linq queries. However, our attempts to generalize query generation resulted in bad performance due to EF being confused by the resulting complex expressions, so in the end horrible SQL was produced.
We resorted to Entity SQL.
Not sure if you are using MS SQL. Seems SQL could do most of the work for you, and you can build dynamic queries. Obviously the select/from statement needs work, but you can get the idea from the where clause.
DECLARE #SEARCHTYPE VARCHAR(20)
DECLARE #SEARCHTERM VARCHAR(100)
SELECT
[FIELDS]
FROM
[TABLE]
WHERE
(#SEARCHTYPE = 'BEGINSWITH' AND [FIELD] LIKE #SEARCHTERM + '%') OR
(#SEARCHTYPE = 'ENDSWITH' AND [FIELD] LIKE '%' + #SEARCHTERM) OR
(#SEARCHTYPE = 'EQUALS' AND [FIELD] = #SEARCHTERM)
You could have the first combo data source set to myEntityObject.GetType().GetProperties(), the second to a list of displayable Funcs<string, string, bool>, like this:
public class ComboPredicate
{
public Func<string, string, bool> Func {get; set;}
public string Name {get; set; }
}
Later, when you load the form:
comboProperty.Datasource = myEntityObject.GetType().GetProperties()
comboOperation.Datasource = new List<Predicate>
{
{
Name = "Contains",
Predicate = (s1, s2) => s1 != null && s1.Contains(s2),
},
{
Name = "Equals",
Predicate = (s1, s2) => string.Compare(s1, s2) == 0,
},
//...
}
And later, when you want to select your entities:
var propertyInfo = (PropertyInfo)comboProperty.SelectedValue;
var predicate = ((ComboPredicate)comboOperation.SelectedValue).Predicate;
var filteredObjects = objects.Where(o => predicate(propertyInfo.GetValue(o, null).ToString(), textBoxValue.Text));
create method and call it on button click demo below
public List gettaskssdata(int c, int userid, string a, string StartDate, string EndDate, string ProjectID, string statusid)
{
List<tbltask> tbtask = new List<tbltask>();
var selectproject = entity.tbluserprojects.Where(x => x.user_id == userid).Select(x => x.Projectid);
if (statusid != "" && ProjectID != "" && a != "" && StartDate != "" && EndDate != "")
{
int pid = Convert.ToInt32(ProjectID);
int sid = Convert.ToInt32(statusid);
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid) && (x.tblstatu.StatusId == sid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else if (statusid == "" && ProjectID != "" && a != "" && StartDate != "" && EndDate != "")
{
int pid = Convert.ToInt32(ProjectID);
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else if (ProjectID == "" && statusid != "" && a != "" && StartDate != "" && EndDate != "")
{
int sid = Convert.ToInt32(statusid);
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblstatu.StatusId == sid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else if(ProjectID!="" && StartDate == "" && EndDate == "" && statusid == "" && a == "")
{
int pid = Convert.ToInt32(ProjectID);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid)).OrderByDescending(x => x.ProjectId).ToList();
}
else if(statusid!="" && ProjectID=="" && StartDate == "" && EndDate == "" && a == "")
{
int sid = Convert.ToInt32(statusid);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblstatu.StatusId == sid) ).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a == "" && StartDate != "" && EndDate != "" && ProjectID != "")
{
int pid = Convert.ToInt32(ProjectID);
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.ProjectId == pid) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else if (StartDate == "" && EndDate == "" && statusid != "" && ProjectID != "" && a != "")
{
int pid = Convert.ToInt32(ProjectID);
int sid = Convert.ToInt32(statusid);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid) && (x.tblstatu.StatusId == sid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a))).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a == "" && StartDate == "" && EndDate == "" && ProjectID != "" && statusid != "")
{
int pid = Convert.ToInt32(ProjectID);
int sid = Convert.ToInt32(statusid);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Include(x => x.tblstatu).Where(x => selectproject.Contains(x.ProjectId) && x.tblproject.company_id == c && x.tblproject.ProjectId == pid && x.tblstatu.StatusId == sid).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a != "" && StartDate == "" && EndDate == "" && ProjectID == "" && statusid == "")
{
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a))).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a != "" && ProjectID != "" && StartDate == "" && EndDate == "" && statusid == "")
{
int pid = Convert.ToInt32(ProjectID);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a))).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a != "" && StartDate != "" && EndDate != "" && ProjectID == "" && statusid == "")
{
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else
{
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && x.tblproject.company_id == c).OrderByDescending(x => x.ProjectId).ToList();
}
return tbtask;
}