How to find the data between month in entityframework? - asp.net-mvc

I had requirement to display the data of this month (between month starting to ending data )
I know how to do in MySQL below query
enter code here select #MonthAmount := IFNULL(sum(AmountReceived), 0.0) as TotoalAmountperMonth
from collection
where date_time between DATE_FORMAT(NOW() ,'%Y-%m-01')
and LAST_DAY(now() - interval 0 month ) and AgentID=v_agent) as monthamount
but how to do using entity (lambda expression) I am new to entity when I google I got to get the data of today but in month?
below query got the result of today data
enter code here var newAuctionsResults = repo.FindAllAuctions()
.Where(a => a.IsActive == true
|| (a.StartTime.Value.Year == todayYear
&& a.StartTime.Value.Month == todayMonth
&& a.StartTime.Value.Day == todayDay))
.ToList();

Try
DateTime date = DateTime.Today;
var newAuctionsResults = repo.FindAllAuctions()
.Where(a => a.StartTime.Value.Year == date.Year
&& a.StartTime.Value.Month == date.Month)

Related

Date Filter is not working properly MVC

My date filter works just fine when I put it into a separate view, but I am having trouble merging it with the other filters and I am not sure where I am going wrong. All other filters are working. Could you please take a look and let me know what I need to change when I join my query to the others to get it working and merged? Thank you!
Here is what it looks like in a separate Controller, and this works in the view:
public ActionResult DateFilter(FormCollection DatePicker)
{
DateTime start = DateTime.Today;
DateTime end = DateTime.Today;
if (DatePicker.Count > 0)
{
start = DateTime.Parse(DatePicker["startDate"].ToString());
end = DateTime.Parse(DatePicker["endDate"].ToString());
}
var Issue = db.Issue.Where(d => d.DateCreated >= start && d.DateCreated <= end).Select(i => new IssueViewModel
{
Name = i.Name,
Description = i.Description,
DateCreated = i.DateCreated,
DateCompleted = i.DateCompleted,
//ect.
}).ToList();
ViewBag.Issue = Issue;
return View();
}
Here is what it looks like merged with the other filters:
private static IQueryable<Issue> FilterDeviceList(List<Issue> issues, FormCollection DatePicker, string EHP, string IssueKey)
{
var query = issue.AsQueryable();
//COPYING STARTS HERE
DateTime start = DateTime.Today;
DateTime end = DateTime.Today;
if (DatePicker.Count > 0)
{
start = DateTime.Parse(DatePicker["startDate"].ToString());
end = DateTime.Parse(DatePicker["endDate"].ToString());
}
query = query.Where(d => d.DateCreated >= start != null && d.DateCreated <= end != null && d.DateCreated == Convert.ToDateTime(DatePicker));
//COPYING ENDS HERE
if (!string.IsNullOrWhiteSpace(EHP))
query = query.Where(i => i.EHPP != null && i.EHPP == (EHP == "1" ? false : true));
if (!string.IsNullOrWhiteSpace(IssueKey))
query = query.Where(i => i.IssueKey != null && i.IssueKey.Contains(IssueKey));
return query;
}
If anyone needs to see the view or the controller that calls IQueryable, please let me know and I can post it, but I think this should be sufficient. Thank you again! :)
Try this:
private static IQueryable<Issue> FilterDeviceList(List<Issue> issues, FormCollection DatePicker, string EHP, string IssueKey)
{
var query = issues.AsQueryable();
DateTime start,end;
if (DatePicker.Count > 0)
{
start = DateTime.ParseExact(DatePicker["startDate"].ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
end = DateTime.ParseExact(DatePicker["endDate"].ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
}
// assuming start and end date will not be null
if(start != null && end !=null)
{
query = query.Where(d => d.DateCreated >= start && d.DateCreated <= end);
}
if (!string.IsNullOrWhiteSpace(EHP))
query = query.Where(i => i.EHPP != null && i.EHPP == (EHP == "1" ? false : true));
if (!string.IsNullOrWhiteSpace(IssueKey))
query = query.Where(i => i.IssueKey != null && i.IssueKey.Contains(IssueKey));
return query;
}

linq: how to get sorted records from last ID

I have the following table,
ItemTable,
Col1 : ItemID(int)
Col2 : MRP(Decimal)
To one of the application I needed to pass selected number of items at a time, They will send me the lastId which I passed to them, the initial requirement was to pass the newest items, which I was able to get it using following query,
var itemList = itemRepository.AsQueryable()
.Where(r => r.ProductID == productID && r.IsActive == true && r.ItemID< lastId)
.OrderByDescending(r => r.ItemID)
.Take(numberOfItems)
.ToList();
However now there is a sort option added to it, which is the MRP column, though again i have only the last Id with me, how could I will able to get this? I tried with the following query, no luck.
var itemList = itemRepository.AsQueryable()
.Where(r => r.ProductID == productID && r.IsActive == true && r.ItemID< lastId)
.OrderByDescending(r => r.ItemID)
.OrderBy(r => r.MRP)
.Take(numberOfItems)
.ToList();
UPDATE : Working Code
As per CamperWill's suggesstion I updated my code and works great with skip.
var itemList = itemRepository.AsQueryable()
.Where(r => r.ProductID == productID && r.IsActive == true)
.OrderBy(r => r.MRP)
.Skip(pageNumber * numberOfItems)
.Take(numberOfItems)
.ToList();
LastID will not help you with paging if you are sorting by a different field (MRP). Also, as indicated in the comments above, the first ordering is effectively ignored by adding the second.
You could consider tracking the page number that is requested and use the Skip() extension.
// input parameter 'page'
var itemList = itemRepository.AsQueryable()
.Where(r => r.ProductID == productID && r.IsActive == true)
.OrderBy(r => r.MRP)
.Skip( (page-1)*numberOfItems )
.Take(numberOfItems)
.ToList();

List recent records(MVC)

I would like to create a model to list recent 5 appointments from appointment table(date,description,status fields).I have Patient and Appointment tables.Here is the code but I think some part missings
public ActionResult Recent(Models.AppModel User)
{
if (Session["UserEmail"] != null)
{
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email ==(String)Session["UserEmail"]);
var list = (from m in db.Appointments
where m.PatientNo == patient.PatientNo && m.Date<Current.Date
select m.ToList());
}}
return View();}
I assume Current is DateTime.Now ?
Your filtering (m.Date<Current.Date) will select all items whose date is before this point in time. Not just recent items, but any item with a past date.
The question is, what is your criterium for 'recent'?
'recent' = The last 7 days
DateTime Current = DateTime.Now;
DateTime Past = DateTime.Now.AddDays(-7);
... m.Date < Current && m.Date > Past ...
'recent' = The last 20 items (regardless of how old they are)
DateTime Current = DateTime.Now;
db.Appointments.Where(m => m.Date < Current.Date)
.OrderByDescending(x => m.Date)
.Take(20)
.ToList();
If you have another criterium for what a 'recent' appointment is, please elaborate :)

How to get distinct value from the list

I have a List generated from Linq to Entities query. In which, I need to get a unique records based on BibId. I have tried changing the query but no help to get the unique records based on BibId.
Query
aa.NewBibContentsModel = (from x in db.BibContents
where (x.TagNo == "245" && x.NormValue == aa.CurrentTitle) || (x.TagNo == "020" && x.NormValue == aa.CurrentISBN) || (x.TagNo == "022" && x.NormValue == aa.CurrentISBN)
select new
{
BibId = x.BibId,
Title = (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == "245" orderby a.Id ascending select a.NormValue),
//Tit = (from a in db.BibContents where a.BibId == line.BibId && a.TagNo == "245" && a.Sfld == "a" select a.NormValue).FirstOrDefault(),
Author = (from a in db.BibContents where a.BibId == x.BibId && splitted.Contains(a.TagNo) && a.NormValue != null select a.TagNo).FirstOrDefault(),
ISBN = (from a in db.BibContents where a.BibId == x.BibId && a.NormValue != null && (a.TagNo == "020" || a.TagNo == "022") orderby a.Id ascending select a.NormValue)
}).AsEnumerable().Select(x => new BibContentsModel
{
BibId = x.BibId,
Title = string.Join(" ", x.Title),
Author = string.Join(" ", (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == x.Author orderby a.Id select a.NormValue)),
ISBN = string.Join(" ", x.ISBN)
}).ToList();
Any help to this problem will be appreciated.
Thanks
What you're trying to achieve is know as Distinct By. MoreLinq has a function for it. The syntax would look like:
(from x in db.BibContentsNo == "022")
... // your query
}).AsEnumerable()
.DistinctBy(x => x.BibId) // <= MoreLinq
What is does is group the records by BibId and take the first element of each group.
You can download MoreLinq as a NuGet package.

Grails - find where date ranges overlap

I have a Grails domain object with a startDate and endDate property.
What's the best way to find all those objects where the range [startDate, endDate] overlaps with a specified date range? I know how to do this in SQL but wonder if there's any Grails/GORM magic to do it more succinctly.
Also, the endDate is an optional property.
The SQL / JPQL query would be something like
from MyObject obj where obj.startDate <= ?1 and (obj.endDate is null OR obj.endDate >= ?2)
Two Ways to embrace Grails/GORM in this case:
Lazy:-
def today = new Date()
def query = MyObject.where {
startDate <= (today - 10) && (endDate == null || endDate >= today + 10)
}
def listOfMyObjects = query.list()
Eager:-
def today = new Date()
def listOfMyObjects = MyObject.findAll {//or find{} if you need the first occurance
startDate <= (today - 10) && (endDate == null || endDate >= today + 10)
}

Resources