Convert sql to entity in query syntax - asp.net

How can i convert the following query to entity framework in query syntax..
SELECT MIN(Date) StartDate, MAX(Date) EndDate, Title, Flag FROM
Holiday GROUP BY Title, Flag
Any help?

After a hard time i get the solution
(from e in db.Holidays
group e by new {e.Title, e.Flag}
into g
select new AllEventViewModel
{
start = g.Max(e=>e.Date),
end = g.Min(e => e.Date),
title = g.Key.Title,
Flag = g.Key.Flag
}).AsEnumerable();

var results = db.holidays.GroupBy(g => new { g.Title, g.Flag }).Select(k => new
{
MinDate = k.Min(a => a.Date),
StartDate = k.FirstOrDefault().StartDate,
MaxDate = k.Max(b => b.Date),
EndDate = k.FirstOrDefault().EndDate,
Title = k.Key.Title,
Flag = k.Key.Flag
}).ToList();

Related

How to assign key and count to two different labels asp.net

I have this query:
var months = dates.GroupBy(
x => x.Value.Month).Select(g => new { Month = g.Key, Count = g.Count()});
lbl1.Text = string.Join(",", months);
How do I assign key and count to two different labels?
Try this
lblMonth.Text=months.Month;
lblCount.Text=months.Count;
Also you have to call FirstOrDefault() or ToList() in order to select data. Currently you code will not select data.
var months = dates.GroupBy(x => x.Value.Month).Select(g => new { Month = g.Key, Count = g.Count() }).FirstOrDefault();
OR
var months = dates.GroupBy(x => x.Value.Month).Select(g => new { Month = g.Key, Count = g.Count() }).ToList();
if you use ToList() than you will have to get values by index like
lblMonth.Text=months[0].Month;
lblCount.Text=months[0].Count;

Why is my query not returning distinct rows?

Afternoon,
I am trying to return a list of products from my SQL Server 2008 R2 database but I only want to return the results with the latest date.
However the code below seems to return all items, even the ones with an older date. How do I go about getting my results with just the latest date.
var query = (from a in dc.aboProducts
join t in dc.twProducts on a.sku equals t.sku
join lp in dc.LowestPrices on a.asin equals lp.productAsin
select new GetLowestPrices
{
productAsin = lp.productAsin,
sku = t.sku,
title = t.title,
twprice = Convert.ToString(t.twPrice),
lowprice = Convert.ToString(lp.price),
amzprice = Convert.ToString(lp.tweAmzPrice),
lastupdated = Convert.ToDateTime(lp.priceDate)
}).Distinct().OrderBy(ti => ti.title);
return query.ToList();
Try something like this:
var query =
from a in dc.aboProducts
join t in dc.twProducts on a.sku equals t.sku
join lp in dc.LowestPrices on a.asin equals lp.productAsin
select new GetLowestPrices
{
productAsin = lp.productAsin,
sku = t.sku,
title = t.title,
twprice = Convert.ToString(t.twPrice),
lowprice = Convert.ToString(lp.price),
amzprice = Convert.ToString(lp.tweAmzPrice),
lastupdated = Convert.ToDateTime(lp.priceDate)
};
var lookup =
query
.ToLookup(x => x.sku)
.Select(x => x.OrderByDescending(y => y.lastupdated).First())
.OrderBy(x => x.title);
return lookup.ToList();
Because the Distinct is not applied on the existing list, but create a new one, and you need to get it on a new list as:
val DistinctList = ExistingList.Distinct().ToList();

How to calculate count on of table column using group by clause in linq

I'm new to linq.
In c# I'm doing as follows to get the count of one column.
SELECT DispatcherName,
ActivityType,
CONVERT(BIGINT,COUNT(ActivityType)) AS Total
FROM ACTIVITYLOG
GROUP BY DispatcherName,
ActivityType
ORDER BY Total DESC
Can any one tell m,how I can achieve the same thing using LINQ.
Update:
HI I did as follows and got the reslut.
But I'm not able to convert result to datatable.
this is how I did.
here dt is datatabe with two columns Dispatchername and ActivityType.
var query1 = from p in dt.AsEnumerable()
group p by new
{
DispatcherName = p.Field<string>("Dispatchername"),
Activity = p.Field<string>("ActivityType"),
}
into pgroup
let count = pgroup.Count()
orderby count
select new
{
Count = count,
DispatcherName = pgroup.Key.DispatcherName,
Activity = pgroup.Key.Activity
};
pls help me out asap.
from c in ACTIVITYLOG
group c by new {c.DispatcherName, c.ActivityType} into g
orderby g.Count() descending
select new { g.Key.DispatcherName, g.Key.ActivityType, Total = g.Count() }
If you want your results returned back to a DataTable, one option is to use the CopyToDataTable method.
Here's a live example: http://rextester.com/XHX48973
This method basically requires you to create a dummy table in order to use its NewRow method - the only way to create a DataRow, which is required by CopyToDataTable.
var result = dt.AsEnumerable()
.GroupBy(p => new {
DispatcherName = p.Field<string>("DispatcherName"),
Activity = p.Field<string>("ActivityType")})
.Select(p => {
var row = dummy.NewRow();
row["Activity"] = p.Key.Activity;
row["DispatcherName"] = p.Key.DispatcherName;
row["Count"] = p.Count();
return row;
})
.CopyToDataTable();
Perhaps a better way might be just fill in the rows directly, by converting to a List<T> and then using ForEach.
DataTable dummy = new DataTable();
dummy.Columns.Add("DispatcherName",typeof(string));
dummy.Columns.Add("Activity",typeof(string));
dummy.Columns.Add("Count",typeof(int));
dt.AsEnumerable()
.GroupBy(p => new { DispatcherName = p.Field<string>("DispatcherName"),
Activity = p.Field<string>("ActivityType")})
.ToList()
.ForEach(p => {
var row = dummy.NewRow();
row["Activity"] = p.Key.Activity;
row["DispatcherName"] = p.Key.DispatcherName;
row["Count"] = p.Count();
dummy.Rows.Add(row);
});
Live example: http://rextester.com/TFZNEO48009
This should do the trick:
IList<ACTIVITYLOG> allActivityLogs;
var result = (from c in allActivityLogs
select new
{
DispatcherName = c.DispatcherName,
ActivityType = c.ActivityType,
Total = c.ActivityType.Count
}).OrderByDescending(x => x.Total)
.GroupBy(x => new { x.DispatcherName, x.ActivityType });
You only need to substitute the allActivityLogs collection with the actual collection of your entities.

Entity Framework query syntax

I having a trouble with a query
I need to take out the SHIPMENT from GetAllOrderData - the same place where you can find POD_DATE and RECEIVE_NAME...but I get an error
Error 1 The name 'x' does not exist in the current context
My code is:
public IEnumerable<ReportItemDTO> GetTaskProgress(DateTime targetDate)
{
try
{
var startDate = targetDate.Date;
var endDate = startDate.AddDays(1);
OrderDataRepository rep = new OrderDataRepository();
var query = rep.GetAllOrderData()
.Where(x => x.POD_DATE >= startDate && x.POD_DATE <= endDate)
.GroupBy(o => o.User)
.Select(g => new ReportItemDTO
{
DriverId = g.Key.Id,
PdriverName = g.Key.Name,
OrderCount = g.Count(),
ReportedOrdersCount = g.Count(o => o.RECEIVE_NAME != null),
SHIPMENT = (x.SHIPMENT)
} );
return query;
SHIPMENT = (x.SHIPMENT)
Well you are within a grouping when you try to make that assignment - there are many shipments in each grouping not just one - in fact all shipments for that particular user. Assuming you want a collection of them you could do:
Shipments = g.Select( x=> x.SHIPMENT)
Edit:
If you just want the first shipment for each user (somewhat illogical but fits your data model):
SHIPMENT = g.Select( x=> x.SHIPMENT).First()

LINQ group by and compare date

I have the following:
var currentDate = DateTime.UtcNow;
var calendarEntry = from item in new CalendarEntryRepository(this.Db).List().Where(x => x.Culture == language.Value)
group item by item.ContentObjectId into g
let itemMaxDate = g.Where(i => i.StartDate > currentDate).Select(i => i.StartDate).DefaultIfEmpty()
let city = g.Select(i => i.City).FirstOrDefault()
select new
{
ContentObjectId = g.Key,
StartDate = itemMaxDate,
City = city ?? string.Empty
};
From CalendarEntryRepository I want to group by ContentObjectId (this works fine). However when i add this line:
let itemMaxDate = g.Where(i => i.StartDate > currentDate).Select(i => i.StartDate).DefaultIfEmpty()
I keep getting this error:
Message = "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value."
What i'm trying to do is group by ContentObjectId and then get StartDate that is greater than today.
I'm using entity framwork and MS SQL2008
thanks
The Min Value of DateTime in your database has a lower value that the MinValue defined int he culture you used in your App.
Change the StartDate column in DataBase to data type DateTime2 to support a broader range of dates

Resources