Here is my query...
var salesSelection = (from a in crmDBContext.Quotes
where a.quoteDate >= startDate && a.quoteDate <= endDate && a.region == regionselect
group a by new { a.customerNumber } into queryOut
select new { queryOut.Key.customerNumber,
totalQuantity = queryOut.Sum(q => int.Parse(q.itemQuantity)),
totalPrice = queryOut.Sum(s => s.price) }).OrderByDescending(i => i.totalPrice);
I get an error that linq doesn't recognize the method.
I have also tried
totalQuantity = queryOut.Sum(q => Convert.ToInt32(q.itemQuantity)).
I am not allowed to change the actual column in the table in the database to reflect the quantity as an integer instead of a string as the table updates daily from our mainframe.
Is there a way to do this conversion inside of the linq query, and if not, is there a way to retrieve all of the quantities and sum them later without having to requery?
I want to take records in a database over the past year, sum the records by month, and then populate a line graph with that information. However, when a month has no records, I can't seem to figure out how to get that into the proper location in the list. For example, if nothing exists for September or October, my line graph just skips those months. I tried checking and adding the months in afterwards, but I can't get them in sequential order. Any help?
Dim PointTotals = db.MemberRewards _
.Where(Function(r) sitewideFilterSelectedMemberIds.Contains(r.memberId) And r.supplier.name <> "AudStandard" And r.transactionDate >= startDate And r.transactionDate <= EndDate) _
.GroupBy(Function(r) New With {r.transactionDate.Value.Month, r.transactionDate.Value.Year}) _
.Select(Function(gr) New With {.month = gr.Key.Month, .year = gr.Key.Year, .totalPoints = gr.Sum(Function(r) r.points)}) _
.OrderBy(Function(gr) gr.year).ThenBy(Function(gr) gr.month)
Dim firstPeriodDate As Date
Dim currentDate As Date = DateAdd(DateInterval.Month, -1, startDate)
If PointTotals.Count > 0 Then
Dim firstPeriod = PointTotals.First
firstPeriodDate = CDate(firstPeriod.month & "/1/" & firstPeriod.year)
Else
firstPeriodDate = EndDate
End If
Dim months As New List(Of String)
Dim Points As New List(Of Integer)
Do While currentDate < firstPeriodDate
months.Add(currentDate.ToString("MMM"))
Points.Add(0)
currentDate = DateAdd(DateInterval.Month, 1, currentDate)
Loop
For Each period In PointTotals
months.Add(CDate(period.month & "/1/" & period.year).ToString("MMM"))
Points.Add(period.totalPoints)
Next
ViewBag.Months = """" & String.Join(""",""", months.ToArray) & """"
ViewBag.Points = String.Join(",", Points.ToArray)
I think this is a more elegant solution than trying to clean up the list after the loop. The only changes to your code are just before, and in, the For Each Period loop.
Dim PointTotals = db.MemberRewards _
.Where(Function(r) sitewideFilterSelectedMemberIds.Contains(r.memberId) And r.supplier.name <> "AudStandard" And r.transactionDate >= startDate And r.transactionDate <= EndDate) _
.GroupBy(Function(r) New With {r.transactionDate.Value.Month, r.transactionDate.Value.Year}) _
.Select(Function(gr) New With {.month = gr.Key.Month, .year = gr.Key.Year, .totalPoints = gr.Sum(Function(r) r.points)}) _
.OrderBy(Function(gr) gr.year).ThenBy(Function(gr) gr.month)
Dim firstPeriodDate As Date
Dim currentDate As Date = DateAdd(DateInterval.Month, -1, startDate)
If PointTotals.Count > 0 Then
Dim firstPeriod = PointTotals.First
firstPeriodDate = CDate(firstPeriod.month & "/1/" & firstPeriod.year)
Else
firstPeriodDate = EndDate
End If
Dim months As New List(Of String)
Dim Points As New List(Of Integer)
Do While currentDate < firstPeriodDate
months.Add(currentDate.ToString("MMM"))
Points.Add(0)
currentDate = DateAdd(DateInterval.Month, 1, currentDate)
Loop
Dim thisPeriodDate As Date
Dim previousPeriodDate As Date = currentDate
For Each period In PointTotals
thisPeriodDate = CDate(period.month & "/1/" & period.year)
Do While DateDiff(DateInterval.Month, previousPeriodDate, thisPeriodDate) > 1
months.Add(previousPeriodDate.ToString("MMM"))
Points.Add(0)
previousPeriodDate = DateAdd(DateInterval.Month, 1, previousPeriodDate)
Loop
months.Add(thisPeriodDate)
Points.Add(period.totalPoints)
previousPeriodDate = DateAdd(DateInterval.Month, 1, previousPeriodDate)
Next
ViewBag.Months = """" & String.Join(""",""", months.ToArray) & """"
ViewBag.Points = String.Join(",", Points.ToArray)
It sounds like that in your code to add missing months you used the .Add method. You would need to use months.Insert(position, CDate(....)) and Points.Insert(position, 0) where position is the correct index to insert the month in the correct order.
I could give you exact commands but you didn't include the cleanup code you referenced in the question.
There's a lot of approaches that you can take to solve this, I'll offer a DB one.
Since you're connecting to a database to pull your data, you can also do your summations/groupings on the DB side.
You can do this in 3 steps:
1) get a distinct list of all your months and store them in a temp table
2) create your summations by month, and store them in another temp table
3) left join step 1 on step 2 (using month as join criteria), order in whatever order you care about, and now you have all your months.
There are a lot of ways to implement this on the SQL side, the approach above was just one I thought would be easy to follow.
I am working on news function. News model contains publishing date....
Is there a way to filter my record from db on the base of Publishing Date's day name such as in controller action:
var data1 = db.News.Where(x => x.PublishingDate >= DateTime.Now
&& x.PublishingDate.Day == (int)DayOfWeek.Sunday);
ViewBag.SundayNews = data1;
Or if there is another way around or any reference.
Try this solution: http://c-sharp-snippets.blogspot.ru/2011/12/getting-dayofweek-in-linq-to-entities.html
var firstSunday = new DateTime(1753, 1, 7);
var filtered = from e in dbContext.Entities
where EntityFunctions.DiffDays(firstSunday, e.SomeDate) % 7 == (int)DayOfWeek.Monday
select e;
firstSunday stores the minimal value for MS SQL DATETIME type.
I've tried to combine my Doctrine_Query and sfDoctrinePager, but when I fetch the results, it's always return one row (when I run the generated query in my database it was normal)
this is my code:
$pelanggan = Doctrine_Query::create()
->addSelect('l.id as id_transaksi,
l.jenis_bbm as jenis_bbm,
SUM(volume) as vol,
k.nama_kapal as nama_kapal
')
->from('laut_request_message l')->innerJoin('l.Kapal k')
->groupBy('l.id_kartu')
->orderBy('id_edc')
->where('volume > 0');
$pager = new sfDoctrinePager('laut_request_message', sfConfig::get('app_max_row_per_page',20));
$pager->setPage($request->getParameter('page',1));
$pager->setQuery($pelanggan);
$pager->init();
When i get the total row using $pager->count() it return all row in that query, but when I get the total result in the current page (count($pager->getResults()) it is only return a row.
Could you guys give me an advice? or may be another solutions ?
I have the following SQL command:
SELECT CONVERT(varchar, Logged, 103) AS Visited, COUNT(ID) AS Totals
FROM tblStats
GROUP BY CONVERT(varchar, Logged, 103)
ORDER BY Visited DESC
I want to translate this into a L2S statement that can be used with the Entity Framework, but in working with datetime types, I'm getting various errors depending on how I try to attack the problem.
Approach:
var results = from s in db.Stats
group s by (s.Logged.Date.ToString()) into Grp
select new { Day = Grp.Key, Total = Grp.Count() };
Error:
LINQ to Entities does not recognize
the method 'System.String ToString()'
method, and this method cannot be
translated into a store expression.
Approach:
var results = from s in db.Stats
group s by (s.Logged.Date) into Grp
select new { Day = Grp.Key, Total = Grp.Count() };
Error:
The specified type member 'Date' is
not supported in LINQ to Entities.
Only initializers, entity members, and
entity navigation properties are
supported.
What syntax do I need to make the query work?
Try using the EntityFunctions.TruncateTime method:
var results = from s in db.Stats
group s by EntityFunctions.TruncateTime(s.Logged) into Grp
select new { Day = Grp.Key, Total = Grp.Count() };
Do you need the Date section in s.Logged.Date?
Have you tried this:
var results = from s in db.Stats
group s by (s.Logged) into Grp
select new { Day = Grp.Key, Total = Grp.Count() };
I'm assuming that Logged is the property (column in the table).
EDIT: you guys are way to quick.