runtime Type Error in F# Linq Sql query with group by on multiple columns - group-by

I implemented a Linq query in F# that uses this solution to group by multiple columns. It compiles and works half of the time but in the other half of the time the program throws a runtime type miss-match error. Sometimes the AnonymousObject seems to get an int instead of a Nullable<int>, which then causes an error.
let q = query{
for wh in d.Table1 do
where (wh.Date >= vDate)
where (wh.Date <= bDate)
join tae in d.Table2 on
(wh.Table2Key = tae.key)
let key = AnonymousObject<int,int,Nullable<int>>(wh.Table3key,wh.ProjectTableKey,tae.ProjectPhaseKey)
where tae.ProjectPhaseKey.HasValue
groupValBy wh key into g
select {pkey = g.Key.Item2; lphasekey = g.Key.Item3 ; orgk = g.Key.Item1; time = g.Sum (fun x -> x.data) }
}
How can it be, that the types change at runtime? Can anybody give me a hint? Or has an idea how to work around that?

Related

SQL query to include V and E props in the result

I feel like this should be simple, but lots of searching and experimenting has not produced any results.
I have a very simple ODB database with one V and one E class. V has various props and E has one prop: "order"
This simple ODB SQL query...
select expand(out()) from #12:34
...returns all the props from the V records connected by the "out" edges on #12:34 (i.e. the child records of #12:34), working as expected.
But what I'm not able to do is to also include the one prop from those edges, as well as sort by that E prop (which should be trivial once I can get it into the projections).
This works fine in OrientDB v 3.0.0RC2 (the GA will be released in a few days)
MATCH
{class:V, where:(#rid = ?), as:aVertex}.outE(){as:theEdge}.inV(){as:otherVertex}
RETURN theEdge:{*}, otherVertex:{*}
you can also return single properties with
RETURN theEdge.prop1 as p1, theEdge.prop2 as p2, otherVertex.propX as p3

OrientDB create edge between two nodes with the same day of year

I'm interested in creating an edge (u,v) between two nodes of the same class in a graph if they share the same day of year and v.year = u.year+1.
Say I have vertices.csv:
id,date
A,2014-01-02
B,2015-01-02
C,2016-01-02
D,2013-06-01
E,2014-06-01
F,2016-06-01
The edge structure I'd like to see would be this:
A --> B --> C
D --> E
F
Let's set the vertex class to be "myVertex" and edge class to be "myEdge"? Is it possible to generate these edges using the SQL interface?
Based on this question, I started trying something like this:
BEGIN
LET source = SELECT FROM myVertex
LET target = SELECT from myVertex
LET edge = CREATE EDGE myEdge
FROM $source
TO (SELECT FROM $target WHERE $source.date.format('MM-dd') = $target.date.format('MM-dd')
AND $source.date.format('yyyy').asInteger() = $target.date.format('yyyy').asInteger()-1)
COMMIT
Unfortunately, this isn't correct. So I got less ambitious and wanted to see if I can create edges just based on matching day-of-year:
BEGIN
LET source = SELECT FROM myVertex
LET target = SELECT from myVertex
LET edge = CREATE EDGE myEdge FROM $source TO (SELECT FROM $target WHERE $source.date.format('MM-dd') = $target.date.format('MM-dd'))
COMMIT
Which still has errors... I'm sure it's something pretty simple to an experienced OrientDB user.
I thought about putting together a JavaScript function like Michela suggested on this question, but I'd prefer to stick to using the SQL commands as much as possible for now.
Help is greatly appreciated.
Other Stack Overflow References
How to print or log on function javascript OrientDB
I tried with OSQL batch but I think that you can't get what you want.
With whis OSQL batch
begin
let a = select #rid, $a1 as toAdd from test let $a1 = (select from test where date.format("MM") == $parent.$current.date.format("MM") and date.format("dd") == $parent.$current.date.format("dd") and #rid<>$parent.$current.#rid and date.format("yyyy") == sum($parent.$current.date.format("yyyy").asInteger(),1))
commit
return $a
I got this
but the problem is that when you create the edge you can not cycle on the table obtained in the previous step.
I think the best solution is to use an JS server-side function.
Hope it helps.

Entity Framework - TOP using a dynamic query

I'm having issues implementing the TOP or SKIP functionality when building a new object query.
I can't use eSQL because i need to use an "IN" command - which could get quite complex if I loop over the IN and add them all as "OR" parameters.
Code is below :
Using dbcontext As New DB
Dim r As New ObjectQuery(Of recipient)("recipients", dbcontext)
r.Include("jobs")
r.Include("applications")
r = r.Where(Function(w) searchAppIds.Contains(w.job.application_id))
If Not statuses.Count = 0 Then
r = r.Where(Function(w) statuses.Contains(w.status))
End If
If Not dtFrom.DbSelectedDate Is Nothing Then
r = r.Where(Function(w) w.job.create_time >= dtDocFrom.DbSelectedDate)
End If
If Not dtTo.DbSelectedDate Is Nothing Then
r = r.Where(Function(w) w.job.create_time <= dtDocTo.DbSelectedDate)
End If
'a lot more IF conditions to add in additional predicates
grdResults.DataSource = r
grdResults.DataBind()
If I use any form of .Top or .Skip it throws an error : Query builder methods are not supported for LINQ to Entities queries
Is there any way to specify TOP or Limit using this method? I'd like to avoid a query returning 1000's of records if possible. (it's for a user search screen)
Rather than
r = new ObjectQuery<recipient>("recipients", dbContext)
try
r = dbContext.recipients.
.Skip() and .Take() return IOrderedQueriable<T> while .Where returns IQueriable<T>. Thus put the .Skip() and .Take() last.
Also change grdResults.DataSource = r to grdResults.DataSource = r.ToList() to execute the query now. That'll also allow you to temporarily wrap this line in try/catch, which may expose a better message about why it's erroring.
Mark this one down to confusion. I should have been using the .Take instead of .Top or .Limit or anything.
my final part is the below and it works :
grdResults = r.Take(100)

In Linq to EF 4.0, I want to return rows matching a list or all rows if the list is empty. How do I do this in an elegant way?

This sort of thing:
Dim MatchingValues() As Integer = {5, 6, 7}
Return From e in context.entity
Where MatchingValues.Contains(e.Id)
...works great. However, in my case, the values in MatchingValues are provided by the user. If none are provided, all rows ought to be returned. It would be wonderful if I could do this:
Return From e in context.entity
Where (MatchingValues.Length = 0) OrElse (MatchingValues.Contains(e.Id))
Alas, the array length test cannot be converted to SQL. I could, of course, code this:
If MatchingValues.Length = 0 Then
Return From e in context.entity
Else
Return From e in context.entity
Where MatchingValues.Contains(e.Id)
End If
This solution doesn't scale well. My application needs to work with 5 such lists, which means I'd need to code 32 queries, one for every situation.
I could also fill MatchingValues with every existing value when the user doesn't want to use the filter. However, there could be thousands of values in each of the five lists. Again, that's not optimal.
There must be a better way. Ideas?
Give this a try: (Sorry for the C# code, but you get the idea)
IQueryable<T> query = context.Entity;
if (matchingValues.Length < 0) {
query = query.Where(e => matchingValues.Contains(e.Id));
}
You could do this with the other lists aswell.

Add a Date in Linq to Entities

With Linq to Entities, I am trying to query a Log table to find rows near a matching row. I am having trouble with adding a date inside the query. This is what I have so far.
from
l in objectSet.Logs
let
match = objectSet.Logs.Where(whatever).FirstOrDefault()
where
l.Timestamp > (match.Timestamp - twoHours)
&& l.Timestamp < (match.Timestamp + twoHours)
select
l
Leaving out the "whatever" condition that finds the row I'm interested in, "twoHours" has variably been a time span, a .AddHours() function and so forth. I haven't found the right way that EF can generate SQL that adds the value from a field (match.Timestamp) to a constant.
The obvious solution is to do the "match" query first and then use the literal value in a second query, but I have simplified the code example here to the main problem (adding dates in the query) and in actual fact my query is more complex and this would not be ideal.
Cheers
You can generate an AddHours using the EntityFunctions class.
from
l in objectSet.Logs
let
match = objectSet.Logs.Where(whatever).FirstOrDefault()
where
(l.Timestamp > EntityFunctions.AddHours(match.Timestamp, -1 * twoHours))
&& // ...
select
l
However, don't expect this WHERE to be optimized with an index unless you have an expression index on the column.
EntityFunctions is deprecated in favor of DbFunctions
public int GetNumUsersByDay(DateTime Date)
{
using (var context = db)
{
var DateDay = new DateTime(Date.Year, Date.Month, Date.Day);
var DateDayTomorrow = DateDay.AddDays(1);
return context.Users.Where(m => DbFunctions.AddHours(m.DateCreated,-5) >= DateDay && m.DateCreated < DateDayTomorrow).Count();
}
}
As it was described in this article - http://www.devart.com/blogs/dotconnect/?p=2982#first, use parameters (declare variable) instead of DateTime using in your queries.