Linq searches for recent birthdays (within 15 days) - c#

How to use Linq
A table
Field Birthday
Linq searches for recent birthdays (within 15 days)
from a in Employee where a.PositionStatus == true select new{ a.Name,a.Birthday}

Try below query
var fromdate = DateTime.Now;
var todate = DateTime.Now.AddDays(15);
var result =
(
from a in Employee
where a.PositionStuats==true && a.DateOfBirth.Value.Month >= fromdate.Month &&
a.DateOfBirth.Value.Month <= todate.Month &&
a.DateOfBirth.Value.Day >= fromdate.Day && a.DateOfBirth.Value.Day <= todate.Day
select new{ a.Name,a.Birthday}
).ToList();
Depending on your entity frame work version you can also replace a.DateOfBirth.Value.Month with a.DateOfBirth.Month.

Related

how can i wirte linq to compair the year and month f

I am trying to fetch record from my database year and month vise
I have write following linq
Connection cn = new Connection();
IMongoDatabase db = cn.ConnectionString();
var collection = db.GetCollection<HolidayListModel>("Holiday");
var filter = Builders<HolidayListModel>.Filter.Eq("business_id", businessid);
try
{
var obj = collection.Find(filter).ToListAsync();
if (obj != null && obj.Result != null)
{
if (month == "All")
{
holidaylist = obj.Result.Where(x => DateTime.Parse(x.date).Year == selectedyear).OrderBy(x => DateTime.Parse(x.date)).Select(x => new HolidayListModel()
{
_id = x._id,
business_id = x.business_id,
festival = x.festival,
date = x.date,
day = x.day
}).ToList();
}
else
{
holidaylist = (from x in obj.Result where (( x.date == month )) select x).ToList();
}
Here with lambda expression I got the data year vise using query expression I can't find a way to fetch data using year and month
Can someone guide me how can I write linq for this problem
This is usually done simply by using a start/end value; so foo.Year == selectedYear or foo.date == month becomes simply foo >= #start && foo < #end (the end is usually exclusive, so for a "year" check, that would be 1 Jan of the next year; for a "month" check it would be the 1st of the next month; this means that times in the last day are still always treated correctly).
If you are storing your dates in mongodb as strings that are ISO 8601 or similar, you could also do the same thing simply with string comparisons, without any "parse" logic.

Linq Entity Framework grouping and joins on names, year and month

I am developing an ASP.NET MVC Appliction with MYSQL and Entity Framework. I have customers making payments made to some payment categories. I want to develop a ledger where I have customer names and all the classes of payments with total payments made for any particular pay category by each customer. And I will have to group by name, year and month. And be able to filter by year, month or customerid. I have 25 payment categories.
The solution I have made is ancient- it makes use of 25 joins to the get the categories, sum the payments and assign these to a viewmodel. This runs on my developing machine alright but it fails on my server with the error
MySql.Data.MySqlClient.MySqlException: Too high level of nesting for select
Can anyone give me a better approach to achieving this goal
My Code is like below
public ActionResult LedgerReport(int? year, int? month, int? CuId)
{
var query = LedgerYrMn(year, month, CuId);
return View(query);
}
public IEnumerable LedgerYrMn(int? year, int? month, int? CuId)
{
DateTime lastmonth = DateTime.Now;
DateTime thismonth = DateTime.Now;
DateTime thismonthstart = DateTime.Now;
if (year.HasValue && month.HasValue)
{
lastmonth = (new DateTime(year.Value, month.Value, DateTime.DaysInMonth(year.Value, month.Value)).AddMonths(-1));
thismonth = (new DateTime(year.Value, month.Value, DateTime.DaysInMonth(year.Value, month.Value)));
thismonthstart = (new DateTime(year.Value, month.Value, 1));
}
var query =
(
from bk in db.Customers
// pay category 1
join tr in db.Payments
.Where(a => a.PDate <= thismonth && a.PDate >= thismonthstart && a.paycategory.Id == 1 && a.Paid=true)
on bk.CustomerID equals tr.CustomerID into trs
// pay category 2
join tr2 in db.Payments
.Where(a => a.PDate <= thismonth && a.PDate >= thismonthstart && a.paycategory.Id == 2 && a.Paid=true)
on bk.CustomerID equals tr2.CustomerID into trs2
......
etc to the 25 payment categories.
}
select new LedgerViewModel
{
food=(int?)trs.Sum(c => c.Pay) ?? 0,
fuel=(int?)trs.Sum(c => c.Pay) ?? 0
.. etc
});
return query.AsEnumerable();
}

How to convert nested sql statement to linq to entities?

I'm trying to create a basic room availability statement to use with linq to entity framework. I have two tables: 'Room' including columns RoomID/RoomSize and 'Booking' including BookingID/RoomID/StartDate/Enddate.
I have got a working sql statement:
SELECT RoomID, RoomSize from Room
where RoomID NOT IN (SELECT RoomID from booking
where ('08/01/2015' >= [start] AND '08/01/2015' <= [end]) OR ('08/20/2015' >= [start] AND '08/20/2015' <= [end]))
I have got this far with the linq to entity statement:
var rooms = (from r in db.Rooms
where !(((from b in db.Bookings
where (startDate >= b.StartDate && endDate <= b.EndDate) || (endDate >= b.StartDate && endDate <= b.EndDate)).Contains(r.RoomID))
select new AvailableRoom
{
ID = r.RoomID,
Size = r.RoomSize
});
I get an error at the last bracket before .Contains(r.RoomID) saying I should have a select statement but I just can't seem to get it working.
Any suggestions would be welcome.
If you reckon using lambdas would be better/easier please feel free to suggest and example. I'm just not too familiar with them myself.. yet.
Thank you.
You can use LINQ !...Any() for the SQL NOT IN(), like so :
var rooms = (from r in db.Rooms
where !db.Bookings
.Where(b => (startDate >= b.StartDate && endDate <= b.EndDate)
||
(endDate >= b.StartDate && endDate <= b.EndDate)
)
.Any(b => b.RoomID == r.RoomID)
select new AvailableRoom
{
ID = r.RoomID,
Size = r.RoomSize
});

how to select a weeks amount of dates from a database?

What I am trying to do is search my database (ado.net with linq to sql) for all entrys within the last week.
The database has a field called date and I need the entries that are 7 days previous to the current date.
var records = (from r in context.PumpInfoTables
where r.Date.Equals(DateTime.Now)
//&& where r.date <= 7 days <--help
select r);
so I am looking for some help with this query, is there a between function that can be used?
DateTime weekFromNow = DateTime.Now.AddDays(-7);
var records = (from r in context.PumpInfoTables
where r.Date < DateTime.Now
&& r.Date >= weekFromNow
select r);
This is really simple:
var oneWeekAgo = DateTime.Today.AddDays(-7);
var records = (from r in context.PumpInfoTables
where r.Date >= oneWeekAgo
select r);
This assumes that you don't have entries from the future. If you do have, use this instead:
var today = DateTime.Today;
var oneWeekAgo = today.AddDays(-7);
var records = (from r in context.PumpInfoTables
where r.Date >= oneWeekAgo && r.Date <= today + 1
select r);
Please note:
My code uses DateTime.Today instead of DateTime.Now, assuming you are only interested in the date part, not the time.
Something like this?:
var records = (from r in context.PumpInfoTables
where r.Date > DateTime.Today.AddDays(-7)
select r);

How to merge 5 different type of linq queries into one based on a column

I am really confused on a report I need. As of today, most of my reports were simple, so I was able to do them myself easily. But being a newbie in sql/dlinq, I cannot find my way through the following:
var closingStock =
(from p in session.Query<Product>()
select new
{
p.Id,
p.Name,
p.Batch,
p.Rate,
ClosingStock = p.Quantity - p.AllocatedQuantity,
p.DivisionId
}).ToList();
var distributedQuantityAfterPeriod =
(from i in session.Query<OutwardInvoiceItem>()
where i.ParentInvoice.Date > ToDate
select new
{
Id = i.Product.Id,
DistributedAfter = i.Quantity
}).ToList();
var distributedQuantityInPeriod =
(from i in session.Query<OutwardInvoiceItem>()
where i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate
select new
{
Id = i.Product.Id,
Distributed = i.Quantity
}).ToList();
var receivedQuantityAfterPeriod =
(from i in session.Query<InwardInvoiceItem>()
where i.ParentInvoice.Date > ToDate
select new
{
Id = i.Product.Id,
ReceivedAfter = i.Quantity
}).ToList();
var receivedQuantityInPeriod =
(from i in session.Query<InwardInvoiceItem>()
where i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate
select new
{
Id = i.Product.Id,
Received = i.Quantity
}).ToList();
As you can see, I am trying to build a inventory movement report for a specific date. I have the following problems:
1. How can I reduce the five queries? Is it possible?
2. How can I merge the data provided by these queries into one table which is grouped on the product id and summed on the quantity related columns? As of now, I am using for loops which are really slow.
What I am using:
C# 4, nHibernate, Sqlite
Any help will be very highly appreciated.
Regards,
Yogesh.
to reduce roundtrips use .Future() instead of .List()
let all queries return
group i by i.Id into g
select new
{
Id = g.Key,
Quantity = g.Sum(x => x.Quantity)
}).Future();
and do
var alltogether = groupedDistributedQuantityAfterPeriod
.Concat(groupedDistributedQuantityInPeriod)
.Concate(...);
from g in alltogether
group g by g.key into all
select new
{
Id = all.Key,
Quantity = all.Sum(x => x.Quantity)
};
Update:
you can reduce the number of queries with
from i in session.Query<OutwardInvoiceItem>()
where (i.ParentInvoice.Date > ToDate) || (i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate)
select ...
from i in session.Query<InwardInvoiceItem>()
where (i.ParentInvoice.Date > ToDate) || (i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate)
select ...

Categories