how to simplify if else using entity framework - c#

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.

Related

Refactor and reduce cyclomatic complexity with LINQ

I have a method that I feel like could be refactored more efficiently with LINQ.
The purpose of the function is to use some logic to determine which phone number to return. The logic is: Any returned number must be sms_capable. If a number was last used for an rx, use it, otherwise return the first valid number by type in this order: Other, Home, Office
string GetDefaultSMSPhoneNumber(IEnumerable<PhoneNumbers> patientNumbers)
{
const int PHONE_TYPE_HOME = 1;
const int PHONE_TYPE_OFFICE = 3;
const int PHONE_TYPE_OTHER = 9;
var phoneNumberByType = patientNumbers.Where(p => p.sms_capable == 1).GroupBy(p => p.phone_type_id);
// Select the phone number last used in creating a prescription
if (patientNumbers.Where(p => p.sms_capable == 1 && p.last_used_for_rx == 1).Count() > 0)
{
return patientNumbers.Where(p => p.sms_capable == 1 && p.last_used_for_rx == 1).FirstOrDefault().phone_number;
}
// If no number has been used, select a configured SMS number in the following order (Other, Home, Office)
if (patientNumbers.Where(p => p.sms_capable == 1 && p.phone_type_id == PHONE_TYPE_OTHER).Count() > 0)
{
return patientNumbers.Where(p => p.sms_capable == 1 && p.phone_type_id == PHONE_TYPE_OTHER).FirstOrDefault().phone_number;
}
// If no number has been used, select a configured SMS number in the following order (Other, Home, Office)
if (patientNumbers.Where(p => p.sms_capable == 1 && p.phone_type_id == PHONE_TYPE_HOME).Count() > 0)
{
return patientNumbers.Where(p => p.sms_capable == 1 && p.phone_type_id == PHONE_TYPE_HOME).FirstOrDefault().phone_number;
}
// If no number has been used, select a configured SMS number in the following order (Other, Home, Office)
if (patientNumbers.Where(p => p.sms_capable == 1 && p.phone_type_id == PHONE_TYPE_OFFICE).Count() > 0)
{
return patientNumbers.Where(p => p.sms_capable == 1 && p.phone_type_id == PHONE_TYPE_OFFICE).FirstOrDefault().phone_number;
}
return string.Empty;
}
I know the first thing I can do is filter the list to only sms_capable numbers. I feel like I should be able to use .GroupBy to group the numbers by there type, but after they're grouped I'm not sure how to return the first non empty value? I feel like I'm looking for a way to coalesce in linq?
string GetDefaultSMSPhoneNumber(IEnumerable<PhoneNumbers> patientNumbers)
{
const int PHONE_TYPE_HOME = 1;
const int PHONE_TYPE_OFFICE = 3;
const int PHONE_TYPE_OTHER = 9;
var phoneNumberByType = patientNumbers.Where(p => p.sms_capable == 1).GroupBy(p => p.phone_type_id);
var phoneNumber = patientNumbers.FirstOrDefault(p => p.sms_capable == 1 && p.last_used_for_rx == 1)?.phone_number;
// Doesn't work
if (string.IsNullOrEmpty(phoneNumber))
{
var number = phoneNumberByType.FirstOrDefault(p => p.Key == PHONE_TYPE_OTHER && p.Where(x => !string.IsNullOrEmpty(x.phone_number)) ||
(p.Key == PHONE_TYPE_HOME && p.Where(x => !string.IsNullOrEmpty(x.phone_number)) ||
(p.Key == PHONE_TYPE_OFFICE && p.Where(x => !string.IsNullOrEmpty(x.phone_number))));
}
If you need matching against predicates in specific order you can create a collection of Func<PhoneNumbers, bool> and iterate it (also if PhoneNumbers is a class or record then you don't need Count, if it is not, better use Any instead of count):
string GetDefaultSMSPhoneNumber(IEnumerable<PhoneNumbers> patientNumbers)
{
const int PHONE_TYPE_HOME = 1;
const int PHONE_TYPE_OFFICE = 3;
const int PHONE_TYPE_OTHER = 9;
var predicates = new List<Func<PhoneNumbers, bool>>()
{
p => p.sms_capable == 1 && p.last_used_for_rx == 1,
p => p.sms_capable == 1 && p.phone_type_id == PHONE_TYPE_OTHER,
p => p.sms_capable == 1 && p.phone_type_id == PHONE_TYPE_HOME,
p => p.sms_capable == 1 && p.phone_type_id == PHONE_TYPE_OFFICE
}; // Can be moved to static field
// prevent potential multiple materialization of the source
var enumerated = patientNumbers as ICollection<PhoneNumbers> ?? patientNumbers.ToArray();
foreach (var predicate in predicates)
{
var firstOrDefault = enumerated.FirstOrDefault(predicate);
if (firstOrDefault is not null)
{
return firstOrDefault.phone_number;
}
}
return string.Empty;
}
Also in this particular case you can "prefilter" the enumerated with .Where(p => p.sms_capable == 1) to improve performance a bit:
// ...
var enumerated = patientNumbers
.Where(p => p.sms_capable == 1)
.ToArray();
var predicates = new List<Func<PhoneNumbers, bool>>()
{
p => p.last_used_for_rx == 1,
p => p.phone_type_id == PHONE_TYPE_OTHER,
p => p.phone_type_id == PHONE_TYPE_HOME,
p => p.phone_type_id == PHONE_TYPE_OFFICE
};
// ...
This isnt using linq, but you can refactor this by putting some of the complexity into their own methods
private IEnumerable<IGrouping<int, PhoneNumbers>> GetSmsCapablePhoneNumbersByType(IEnumerable<PhoneNumbers> patientNumbers)
{
return patientNumbers.Where(p => p.sms_capable == 1).GroupBy(p => p.phone_type_id);
}
private PhoneNumbers GetLastUsedSmsNumber(IEnumerable<PhoneNumbers> patientNumbers)
{
return patientNumbers.FirstOrDefault(p => p.sms_capable == 1 && p.last_used_for_rx == 1);
}
private PhoneNumbers GetFirstSmsNumberByType(IEnumerable<PhoneNumbers> patientNumbers, int phoneTypeId)
{
return patientNumbers.FirstOrDefault(p => p.sms_capable == 1 && p.phone_type_id == phoneTypeId);
}
public string GetDefaultSMSPhoneNumber(IEnumerable<PhoneNumbers> patientNumbers)
{
var phoneNumberByType = GetSmsCapablePhoneNumbersByType(patientNumbers);
var lastUsedSmsNumber = GetLastUsedSmsNumber(patientNumbers);
if (lastUsedSmsNumber != null)
{
return lastUsedSmsNumber.phone_number;
}
var defaultSmsNumber = GetFirstSmsNumberByType(patientNumbers, PHONE_TYPE_OTHER)
?? GetFirstSmsNumberByType(patientNumbers, PHONE_TYPE_HOME)
?? GetFirstSmsNumberByType(patientNumbers, PHONE_TYPE_OFFICE);
if (defaultSmsNumber != null)
{
return defaultSmsNumber.phone_number;
}
return string.Empty;
}
If you do it correctly, your method names should describe exactly whats happening, so when somone else reads your code they should be able to follow whats happening by reading the method names (This also means there is less need for comments)

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context.:

I have the following code..
var GetStock = db.tabStocks.Where(x => x.SourceDocRef == InvoiceNumber.Text);
List<tabStock> tbs = new List<tabStock>();
foreach (var Stk in GetStock)
{
switch (GetStock.Any(y => y.ProductSKU == Stk.ProductSKU && y.Id != Stk.Id))
{
case true:
if (!(tbs.AsEnumerable().Any(x => x.Id == Stk.Id))) {
tbs.Add(Stk);
}//tbs.AddRange(GetStock2.Where(g => g.ProductSKU == Stk.ProductSKU && g.Id != Stk.Id));
var GetOthers = GetStock.Where(x => x.Id != Stk.Id && x.ProductSKU == Stk.ProductSKU );
foreach (var Gt in GetOthers) {
if (!(tbs.AsEnumerable().Any(x => x.Id == Gt.Id))) {
tbs.Add(Gt);
}
} break;
}
}
//Group and Remove tbs
Literal1.Text += tbs.AsEnumerable().Count();
try
{
var GroupIt = tbs.GroupBy(x => x.ProductSKU ).AsEnumerable()
.Select(g => new tabStock
{
ProductName = g.FirstOrDefault().ProductName,
ProductSKU = g.FirstOrDefault().ProductSKU,
Qty = g.Sum(n => n.Qty).Value,
OutQty = g.Sum(n => n.Qty).Value,
Bal = (db.tabStocks.Any(x => x.ProductSKU == g.FirstOrDefault().ProductSKU && x.SourceDocRef != g.FirstOrDefault().SourceDocRef && x.Id < g.OrderBy(t => t.Id).FirstOrDefault().Id) ? db.tabStocks.Where(x => x.ProductSKU == g.FirstOrDefault().ProductSKU && x.SourceDocRef != g.FirstOrDefault().SourceDocRef && x.Id < g.OrderBy(t => t.Id).FirstOrDefault().Id).OrderByDescending(x => x.Id).FirstOrDefault().Bal - g.Sum(f => f.Qty).Value : (0 - g.Sum(f => f.Qty)).Value).Value,
TransactionRef = g.FirstOrDefault().TransactionRef,
CreatedBy = g.FirstOrDefault().CreatedBy,
CreationDate = g.FirstOrDefault().CreationDate,
SourceDocRef = g.FirstOrDefault().SourceDocRef,
InQty = 0,
transactionType = "Sale",
UnitCost = g.FirstOrDefault().UnitCost.Value,
Received = 0,
TotalValuation = 0,
});
foreach (var NewStk in GroupIt.AsEnumerable())
{
tabStock stk = new tabStock();
stk.ProductName = NewStk.ProductName;
stk.ProductSKU = NewStk.ProductSKU;
stk.Qty = NewStk.Qty;
stk.OutQty = NewStk.OutQty;
stk.Bal = NewStk.Bal;
stk.transactionType = NewStk.transactionType;
stk.TransactionRef = NewStk.TransactionRef;
stk.CreatedBy = NewStk.CreatedBy;
stk.CreationDate = NewStk.CreationDate;
stk.SourceDocRef = NewStk.SourceDocRef;
stk.InQty = NewStk.InQty;
stk.UnitCost = NewStk.UnitCost;
stk.Received = 0;
stk.TotalValuation = 0;
db.tabStocks.Add(stk);
}
foreach (var OldStk in tbs.AsEnumerable())
{
db.tabStocks.Remove(OldStk);
}
db.SaveChanges();
For some reason i have this error:
Unable to create a constant value of type
'Type'. Only primitive types or enumeration types are supported in this context
Can anyone help me point to what this could be. I have looked at a lot of others related, nothing seems to work.. toList(), AsEnumerable(). Where is my code wrong please.

Tidying up lambda expressions

The following code gives me the results I need, but can anyone suggest how to write it better? I'm sure there's a more efficient way to do it.
Thanks.
private bool IsLocation(Guid _vID, Guid OrganisationId)
{
var vehicle = _vehilceRepository.GetSingle(c => c.vehicleId == _vID);
var clients = _clientRepository.GetList(c => c.OrganisationID == OrganisationId);
foreach (var client in clients)
{
var locations = _LocationRepository.GetList(c => c.ClientID == client.ClientID);
if (locations.Count > 0)
{
foreach (var location in locations)
{
if (location.LocationId == vehicle.LocationID)
{
return true;
}
}
}
}
return false;
}
var vehicle = _vehilceRepository.GetSingle(c => c.vehicleId == _vID);
var clients = _clientRepository.GetList(c => c.OrganisationID == OrganisationId);
return clients.SelectMany(client => _LocationRepository.GetList(
c => c.ClientID == client.ClientID))
.Any(location => location.LocationId == vehicle.LocationID);
?

C# search by many parameters Entity Framework 6.0

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 )

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