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 :)
Related
I have the ID of a record I would like to update, However I would only like to edit just one field in this record.
I would like to change the "Availability" field value in the "Vehicles" table from True to False.
How can I go about doing this without changing any other values?
I am using the code first approach and vehicleID holds the Id of the record I want to edit in the "Vehicles" table
var vehicleID = db.RentalAgreements
.Where(x => x.rent_agree_no == merchant_reference)
.Select(x => x.vehicle_id)
.Single();
var d = db.RentalAgreements.Where(x => x.rent_agree_no == merchant_reference).Select(x => x.vehicle_id).Single();
var vehicle_record = db.Vehicles.FirstOrDefault(p => p.vehicle_id == Convert.ToInt32(d));
vehicle_record.Availability = false;
db.SaveChanges();
I'm running the query below to obtain all the events (as a registered student) I'm attending on a specific day and getting an error that says
System.NotSupportedException: Unable to create a constant value of type 'YogaBandy.Models.Profile.YogaProfile'. Only primitive types or enumeration types are supported in this context.
Here is the query I'm using to get all events I'm regsitered for on a specific day.
// my profile
var yogaProfile = dbContext.YogaProfiles.Where(i => i.ApplicationUserId == userId).First();
// events I'm registered for on a specific day
var eventsNew = dbContext.YogaSpaceEvents.Where(
i => i.EventDateTime.Day == date.Day
&& i.EventStatus == YogaSpaceEventStatus.Active
&& i.RegisteredStudentsNew.Contains(yogaProfile)).ToList();
I think it might have something to do with part, but not sure
&& i.RegisteredStudentsNew.Contains(yogaProfile)
FYI - my RegisteredStudentsNew looks like this in the 'YogaSpaceEvents' entity
public virtual ICollection<YogaProfile> RegisteredStudentsNew { get; set; }
and when I add a newly regsitered student I add him/her like this
spaceEvent.RegisteredStudentsNew.Add(yogaProfile);
dbContext.SaveChanges();
Try to move your YogaProfiles.Where(i => i.ApplicationUserId == userId) inside Include statement.
Example:
var eventsNew = dbContext.YogaSpaceEvents
.Include(p=>p.RegisteredStudentsNew.Where(rp => rp.ApplicationUserId == userId))
.Where( i => i.EventDateTime.Day == date.Day
&& i.EventStatus == YogaSpaceEventStatus.Active)
.ToList();
OR
use Any in your where clause
var eventsNew = dbContext.YogaSpaceEvents
.Include(p=>p.RegisteredStudentsNew)
.Where(i => i.EventDateTime.Day == date.Day
&& i.EventStatus == YogaSpaceEventStatus.Active
&& i.RegisteredStudentsNew.Any(rp => rp.ApplicationUserId == userId))
.ToList();
Please read this for why use Include in LINQ.
I am using entityframework in my project.
I have 3 tables which are navigated with many to many relationship.
This is my diagram.
I want to select all my counters id which have last approve status == 15.
I wrote query like this;
var sayacOnayDurumlari =
db.CounterApproveStatus
.Where(x => x.ApproveStatusId == 15).OrderByDescending(x=>x.Id)
.GroupBy(x => x.CountersId)
.Select(e => e.FirstOrDefault());
but it takes my older records which are ID == 15
var son =
db.Counters.Where(
x => x.CounterApproveStatus.OrderByDescending(t => t.Id).FirstOrDefault().ApproveStatusId == 15)
.ToList();
I tried this and I supposed I achieved it. Is it a good query?
You need group first, then find if the latest Id in that group has desired statusId.
Following syntax may not be exactly right, but you could get idea.
var sayacOnayDurumlari =
db.CounterApproveStatus
.GroupBy(x => x.CountersId)
.Select(g => new {
CountersId = g.Key,
LatestRecord = g.OrderByDescending(x=> x.Id)
.FirstOrDefault()
})
.Where(g=> g.LatestRecord.ApproveStatusId == 15)
.Select(g => g.CountersId).ToList();
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();
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)