IQueryable with only optional parameters - c#

I currently have the following method:
public List<Order> GetOrders(int profileId, string timeSpan, string workOrd, string partNo, bool includeDeleted)
{
DateTime startDate = DateTime.Now;
DateTime endDate = DateTime.Now;
string[] times = (!string.IsNullOrWhiteSpace(timeSpan)) ? timeSpan.Trim().Split('-') : new string[] { "", "" };
if (!string.IsNullOrWhiteSpace(times[0]) && !string.IsNullOrWhiteSpace(times[0]))
{
startDate = DateTime.Parse(times[0]).Date;
endDate = DateTime.Parse(times[1]).Date;
}
//New Real Query
IQueryable<Order_Travel> otQuery = _context.Order_Travels.Where(x =>
(profileId != 0 || x.Profile.ProfileID == profileId)
&& ((timeSpan == null || timeSpan.Trim() == "") || ((DbFunctions.TruncateTime(x.TimeRecieved) >= startDate)
&& (DbFunctions.TruncateTime(x.TimeRecieved) <= endDate)))
&& ((workOrd == null || workOrd.Trim() == "") || x.Order.WorkOrdNo == workOrd)
&& ((partNo == null ||partNo.Trim() == "") || x.Order.PartNo == partNo)
&& (!includeDeleted || x.Aborted == true));
//The results is now in order_travel. Under here binding them to a list of orders with only the respective orderTravels included.
List<Order> orders = new List<Order>();
List<Order_Travel> ots = otQuery.ToList();
foreach (Order_Travel ot in ots)
{
var OrderInList = orders.FirstOrDefault(X => X == ot.Order);
if (OrderInList == null)
{
orders.Add(ot.Order);
OrderInList = orders.FirstOrDefault(X => X == ot.Order);
OrderInList.OrderTravels.Clear();
OrderInList.OrderTravels.Add(ot);
}
else
{
OrderInList.OrderTravels.Add(ot);
}
}
return orders;
}
What I need it to do, is (as I've attempted) to make a call, finding all Order_Travel objects that match the paramters sent to it. If some (or all) are left blank, it takes everything, regardless of the values.
The code right now, does not return anything, if a blank search is made (a search that does not have any parameters), and I can not see what could be the issue. I have tried debugging it, but with no luck.
Any help would be greatly appreciated!
Thanks!

Filter one option at a time, instead of trying to put everything into a single expression:
IQueryable<T> query = all; // start with everything
if (IsPresent(option1))
{
query = query.Where(t => t.XXX == option1);
}
Example
IQueryable<Order_Travel> otQuery = _context.Order_Travels;
if (profileId != 0)
{
otQuery = otQuery.Where(x => x.Profile.ProfileID == profileId);
}
if (timeSpan != null && timeSpan.Trim() != "")
{
otQuery = otQuery.Where(x => DbFunctions.TruncateTime(x.TimeRecieved) >= startDate &&
DbFunctions.TruncateTime(x.TimeRecieved) <= endDate);
}
You will also find this easier to maintain than one huge expression.

Probably this part is your problem:
(profileId != 0 || x.Profile.ProfileID == profileId)
It should be
(profileId == 0 || x.Profile.ProfileID == profileId)
If your profile ID is 0, it will only find entries with x.Profile.ProfileID being 0. Probably there are no such entries.

Related

Return the same type for two views from datacontext

I have created two views that return exactly the same columns from the same tables. The only difference between the two views is they filter on different parameters. I have added these into my .dbml file
(Picture of views in dbml) This has then auto generated two classes for these two views.
In my code depending on the value of the property Filter one of the two views is queried, either current or previous. I need these views to be returned as the same type. So that IOrderedQueryable<> items has one return type.
Currently they are returning as either clientOrdersQueryCurrent or clientOrdersQueryPrevious. If I set IOrderedQueryable<> items to either one of these and attempt to cast the other type then this causes a runtime error.
IOrderedQueryable<> items;
bool filterQuery = false;
if (!string.IsNullOrEmpty(OrderNumber) || DateFrom != null || Dateto != null || !string.IsNullOrEmpty(TrackingNumber) || UserId != null)
{
filterQuery = true;
}
if (Filter == "Current")
{
if (filterQuery)
{
items = dataContext.clientOrdersQueryCurrents.Where(o => o.client_id == currentClientIdProvider.GetCurrentClientId()
&& (string.IsNullOrEmpty(OrderNumber) || o.OrderNumber.Contains(OrderNumber))
&& (DateFrom == null || o.OrderPlaced >= DateFrom)
&& (Dateto == null || o.OrderPlaced <= Dateto)
&& (string.IsNullOrEmpty(TrackingNumber) || o.TrackingReference.Contains(TrackingNumber))
&& (UserId == null || o.UserId == UserId)).OrderByDescending(o => o.OrderPlaced);
}
else
{
items = dataContext.clientOrdersQueryCurrents.Where(o => o.client_id == currentClientIdProvider.GetCurrentClientId()).OrderByDescending(o => o.OrderPlaced);
}
}
else if (Filter == "Previous")
{
if (filterQuery)
{
items = dataContext.clientOrdersQueryPrevious.Where(o => o.client_id == currentClientIdProvider.GetCurrentClientId()
&& (string.IsNullOrEmpty(OrderNumber) || o.OrderNumber.Contains(OrderNumber))
&& (DateFrom == null || o.OrderPlaced >= DateFrom)
&& (Dateto == null || o.OrderPlaced <= Dateto)
&& (string.IsNullOrEmpty(TrackingNumber) || o.TrackingReference.Contains(TrackingNumber))
&& (UserId == null || o.UserId == UserId)).OrderByDescending(o => o.OrderPlaced);
}
else
{
items = dataContext.clientOrdersQueryPrevious.Where(o => o.client_id == currentClientIdProvider.GetCurrentClientId()).OrderByDescending(o => o.OrderPlaced);
}
}
else
{
//Default call - current orders
items = dataContext.clientOrdersQueryCurrents.Where(o => o.client_id == currentClientIdProvider.GetCurrentClientId()).OrderByDescending(o => o.OrderPlaced);
}
The only thing I can currently think of to resolve this is to create a class and have the query map the result to the class after it returns.
What is the best way to do this?
The ORM I am currently using is NHibernate.
Better to map to some common class
IOrderedQueryable<CommonItem> items;
items = dataContext.clientOrdersQueryCurrents.Select(e => new CommonItem{...});
...
items = dataContext.clientOrdersQueryPrevious.Select(e => new CommonItem{...});
It can be AutoMapper's ProjectTo method
items = dataContext.clientOrdersQueryPrevious.ProjectTo<CommonItem>();

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.

select records for this month ONLY

List<ActionPerformed> EndOfMonthPLUs = new List<ActionPerformed>();
List<ActionPerformed> AllPLUs = db.ActionPerformeds.ToList();
foreach (ActionPerformed ap in AllPLUs)
{
if (ap.File_Name == "PLU" && ap.Status == "Processed" && ap.Date == ??)
{
EndOfMonthPLUs.Add(ap);
}
}
I also want to add another query: && ap.Date == get all the files for this month.
So I have string date = todaysDate.ToString("MMMM, yyyy");
What now?
Assuming ap.Date is a DateTime, you could check the month and year are identical:
var now = DateTime.Now;
foreach (ActionPerformed ap in AllPLUs)
{
if (ap.File_Name == "PLU"
&& ap.Status == "Processed"
&& ap.Date.Month == now.Month
&& ap.Date.Year == now.Year)
{
EndOfMonthPLUs.Add(ap);
}
}
Compare the Month and Year properties on the Date to those of the current DateTime:
var AllPLUs = db.ActionPerformeds.ToList();
var now = DateTime.Now;
var EndOfMonthPLUs = AllPLUs
.Where(ap =>
ap.File_Name == "PLU" &&
ap.Status == "Processed" &&
ap.Date.Month == now.Month &&
ap.Date.Year == now.Year)
.ToList();
I assume that the "db" variable refers to an Entity Framework context. If so, and if you don't have any further requirements for the list containing ALL the PLUs, you may wish to perform some or all of this filtering as part of the EF query.
If I am not missing something, and your ap.Date property is a DateTime, could you just do this?
foreach (ActionPerformed ap in AllPLUs)
{
if (ap.File_Name == "PLU" && ap.Status == "Processed" &&
ap.Date.Month == DateTime.Today.Month)
{
EndOfMonthPLUs.Add(ap);
}
}
I think that
ap.Date.ToString("MMMM, yyyy") == date
is the answer you're looking for... alternatives could be
ap.Date.Month == DateTime.Now.Month && ap.Date.Year == DateTime.Now.Year
or since you are using entities, a linq query could apply
var aps = from ap in AllPLUs
where ap.File_Name == "PLU"
&& ap.Status == "Processed"
&& ap.Date.Month == DateTime.Now.Month
&& ap.Date.Year == DateTime.Now.Year
select ap
then
foreach(ActionPerformed ap in aps) { }

Return all in List <T> in lambda expression

I'm using lambda expression in LINQ where i have to get all the result when the conditon satisfies if not it should filter.
//Code
List<Dispatch> objDispatch = (List<Dispatch>)Session["Data"];
objDispatch = objDispatch.FindAll(dispatch => dispatch.CustomerTransName == ddlTransporterName.SelectedItem.Text && dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date && dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date);
In the above code i'm filtering the result set with some conditions in that first condition i need a help.
If the transporter name is 'ALL' it should return all the result set it matches with the Date condition or else it should return according to the TransporterName.
How can i achieve this?
With pure logic.
if(ddlTransporterName.SelectedItem.Text == "ALL") {
//return all
} else {
//Do your filter logic
}
Or, with less repitive code:
objDispatch = objDispatch.FindAll(
dispatch => (ddlTransporterName.SelectedItem.Text == "ALL" || dispatch.CustomerTransName == ddlTransporterName.SelectedItem.Text)
&& dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date
&& dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date);
string name = ddlTransporterName.SelectedItem.Text;
objDispatch = objDispatch.FindAll(dispatch =>
(name == "ALL" || dispatch.CustomerTransName == name)
&& dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date
&& dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date);
If transporter name is "ALL" then name OR condition will give true and CustomerTransName will not be checked.
If you want this to be LINQ then you need to actually use a LINQ method e.g. use Where. Also you should do your date conversions once outside if they aren't specific to the row, otherwise they will be converting everytime. Not only that, it makes for more readable code...
var selectedTransporter = ddlTransporterName.SelectedItem.Text;
var fromDate = Convert.ToDateTime(FromDate).Date;
var toDate = Convert.ToDateTime(ToDate).Date;
var query = objDispatch.Where(x => (selectedTransporter == "All" || x.CustomerTransName == selectedTransporter) && x.InvoiceDate.Date >= fromDate && x.InvoiceDate.Date <= toDate);
I think this should suffice:
List<Dispatch> objDispatch = (List<Dispatch>)Session["Data"];
List<Dispatch> filteredDispatches = objDispatch.Where(dispatch => dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date && dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date).ToList();
if (ddlTransporterName.SelectedItem.Text != "ALL")
{
filteredDispatches = filteredDispatches.Where(dispatch => dispatch.CustomerTransName == ddlTransporterName.SelectedItem.Text).ToList();
}
I think something like this should work:
List<Dispatch> objDispatch = (List<Dispatch>)Session["Data"];
var _fromDate = Convert.ToDateTime(FromDate);
var _toDate = Convert.ToDateTime(ToDate);
objDispatch = objDispatch
.FindAll(dispatch => Selector(
dispatch, ddlTransporterName.SelectedItem.Text, _fromDate, _toDate));
static bool Selector(
Dispatch dispatch, string name, DateTime fromDate, DateTime toDate)
{
if (dispatch.CustomerTransName == "ALL")
{
return dispatch.InvoiceDate.Date >= fromDate.Date
&& dispatch.InvoiceDate.Date <= toDate.Date;
}
return dispatch.CustomerTransName == name;
}

How to write Linq expression using external objects

I am trying to convert a loop in to a linq expression. But it seams not to work the way i am doing it:
var customer = GetCustomerFromDatabase(id);
ICollection<Order> customerOrders = null;
if (customer == null)
{
LogAndThrowCustomerNotFound(id);
}
else
{
customerOrders = customer.Orders;
}
customer.YearToDateSales = 0.0;
customer.CurrentSales = 0.0;
DateTime today = DateTime.Now;
if (customerOrders != null)
foreach (var order in customerOrders)
{
if (order.SubmittedDate != null
&& order.SubmittedDate.Value.Year.CompareTo(today.Year) == 0)
{
customer.YearToDateSales += (double)order.OrderTotal;
}
if (order.SubmittedDate != null
&& (order.SubmittedDate.Value.Month.CompareTo(today.Month) == 0
&& order.SubmittedDate.Value.Year.CompareTo(today.Year) == 0))
{
customer.CurrentSales += (double)order.OrderTotal;
}
}
So I came up with that expression to get the customer orders that match the current year... bot it does not work. in he expression order is empty and today is conflicting. I i create
DateTime today = DateTime.Now; in the parm of the expression i get different errors...
IEnumerable<Order> cOrders = customerOrders
.Where((ICollection<Order> order , today) =>
order.SubmittedDate.Value.Month == today.Month);
It's simpler if you just don't attempt pass today into the lambda, it'll be closed into the expression anyway;
customer.YearToDateSales = customerOrders
.Where(x => x.SubmittedDate != null &&
x.SubmittedDate.Value.Year == today.Year)
.Sum(x => x.OrderTotal);
customer.CurrentSales = customerOrders
.Where(x => x.SubmittedDate != null &&
x.SubmittedDate.Value.Month == today.Month &&
x.SubmittedDate.Value.Year == today.Year)
.Sum(x => x.OrderTotal);
Hard to tell exactly what's wrong without the error, but you probably need to check for null on the SubmittedDate like in the original version:
IEnumerable<Order> cOrders = customerOrders
.Where((ICollection<Order> order , today) =>
order.SubmittedDate.HasValue &&
order.SubmittedDate.Value.Month == today.Month);

Categories

Resources