I'm having an error when I'm trying to request data with Linq and entity framework.
Below, the following:
verif = context.DeviceVerifications.Where(d => d.phone == phone
&& d.securityKey == key
&& d.validated == 0
&& (((TimeSpan)(DateTime.Now - d.createDate)).Minutes <= 30)).FirstOrDefault();
The error that shows up is the following: DbArithmeticExpression arguments must have a numeric common type.
I think that the problem comes from that part of the request ((TimeSpan)(DateTime.Now - d.createDate)).Minutes <= 30) but there are the same type on both sides of the comparison.
Does somebody can help me with that ?
Thanks in advance !!
I am not sure whether the ((TimeSpan)(DateTime.Now - d.createDate)).Minutes <= 30) expression can be correctly converted to a storage query.
I would use the DbFunctions.DiffMinutes method
verif = context.DeviceVerifications.Where(d => d.phone == phone
&& d.securityKey == key
&& d.validated == 0
&& DbFunctions.DiffMinutes(DateTime.Now, d.createDate) <= 30)).FirstOrDefault();
Arithmetic with DateTime is not supported in Entity Framework, you have to use DbFunctions.DiffMinutes instead. According to the documentation, when used as part of a LINQ to Entities query, this method invokes the canonical DiffMinutes EDM function to calculate the number of minutes between two time spans.
Related
I am trying to create a Regex expression to validate logical && || string combonation and its corresponding opening and closing () brackets.
I have been messing with the Regex hieroglyphic pattern but can't seem to get it working correctly, mainly due to my complete lack of understanding of the Regex pattern.
After several hours of StackOverflow and google this is what I have so far, I feel I am close.
private void ValidationTest()
{
string hieroglyphics = #"^(?=^[^()]*\((?>[^()]+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))\)[^()]*$)[(]*\d+[)]*(\s+(&&|\|\|)\s+[(]*\d+[)]*)*$";
var tests = new List<string>
{
// Working
"(1 && 2)",
"((1 && 2) && (3 || 4))",
"((1 && 2) && (3 || 4) || ((1 && 2) && (3 || 4)))",
// Not working
"(Stack && Overflow)"
};
if (tests.All(test => Regex.IsMatch(test, hieroglyphics)))
{
MessageBox.Show("Woohoo!!");
}
}
So the main issue with what I have so far is if ther are no brackets 1 && 2 it wont validate, same with (1 && 2) && (3 || 4).
Also it seems to ignore words alltogeter (Stack && Overflow)
Examples of some strings I am tring to validate.
"IsRecording && IsPlaying"
"IsVisible && (IsPlaying && (IsMusic || IsRadio))"
There is also some keywords that contain brakets that could mess things up
Example:
"IsWindowVisible(2) && (IsControlVisible(22) && IsControlFocused(100))"
Edit:
As it is now this expression works fine validating the kind of complexity I need, however the only real issue I have is that its nubers only.
Complex example that validates fine with this Regex
"((1 && 2) && (3 || 4) || ((1 && 2) && (3 || 4)))"
A simple string 1 && 2 wont validate without brakets, but I dont mind adding brackest to these.
all I need is to add support for words instead of just numbers, this will be a fixed list of words if that helps.
If someone can spot the error or point me in a better direction would be awesome
Thanks
Edit:
Answer by mellamokb worked perfect. It seems the trouble was the d+ needed to be 0-9a-zA-Z()
Here is the pattern incase it usefull for anyone else.
string hieroglyphics = #"^(?=^[^()]*(?>[^()]+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))[^()]*$)[(]*[0-9a-zA-Z()]+[)]*(\s+(&&|\|\|)\s+[(]*[0-9a-zA-Z()]+[)]*)*$";
it validates exactly what I need
Examples:
"IsPlayer(Video) && Player(Playing)",
"((IsPlayer(Video) && (Player(Playing) && ControlIsVisible(34))) || (IsPlayer(Video) && (Player(Playing) && ControlIsVisible(34)))) && ControlIsFocused(22)"
I think the reason you are not able to validate expressions without a wrapping () is the wrapping parentheses in your core nesting logic. If you take out the following parentheses I note below, then the other two non-wrapped expressions validate:
^(?=^[^()]*\((?>[^()]+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))\)[^()]*$...
^^ remove this remove this ^^
Then in order to allow expressions that are not just numerical, you need to replace your restrictive \d with a more liberal definition of what you want to validate, say, [0-9a-zA-Z]:
...[(]*\d+[)]*(\s+(&&|\|\|)\s+[(]*\d+[)]*)*$
^^ change these expression ^^
So it would become:
...[(]*[0-9a-zA-Z]+[)]*(\s+(&&|\|\|)\s+[(]*[0-9a-zA-Z]+[)]*)*$
Demo: http://ideone.com/jwkcpL
I've only been playing with linq to sql and lambda expressions for the first time for a few days and I want to do the following.
I've got a string extension method that returns a double. The extension method tests two strings and returns a similarity score.
I have a list of string values from a column in a table using linq to sql and I want to use the extension method as a way of filtering out the only those strings whose similarity score is equal to or greater than the input string.
I've got the below so far. I don't seem to be able to test the value of the returned double.
List<int> ids = dc.ErrorIndexTolerances
.Where(n => n.Token.Distance(s) => .85)
.Select(n => n.ID)
.ToList();
The Distance Method is the extension method that returns a double. Both Token and s are string. ID is an integer ID field within a table.
Does anyone have any tips?
The greater or equal operator is >=, not =>.
List<int> ids =
dc.ErrorIndexTolerances.Where(n => n.Token.Distance(s) >= .85)
.Select(n => n.ID).ToList();
Perhaps this should be
n.Token.Distance(s) >= .85)
Just a typo :-)
Does anyone have any tips?
I have a tip... never use "greater than", only use "less than".
.Where(n => .85 <= n.Token.Distance(s))
I follow this rule mainly because of date logic. When comparing 5 sets of dates, it's good to never make the mistake of mis-reading the sign. The small one is on the left and the big one is on the right, 100% of the time.
.Where(acct => acct.CreateTime <= now
&& acct.StartTime <= order.OrderDate
&& order.FulfilledDate <= acct.EndTime)
say you have something like:
int num = 0
then you do
if(num > 5 || num < 4)
{
...
}
it checks both, but what if you do
if(num < 4 || num > 5)
{
...
}
does it only check the 1st statement?
same as:
if(num > 5 && num == 0)
{
...
}
it should stop after failing the 1st and... right?
This is called boolean short-circuit evaluation and (although [citation-needed]) yes, C# and VB.NET have it (thanks #Lasse for the correction).
In C#, || and && are the short-circuited versions of | and &, respectively
.
Yes, this feature is called short circuit evaluation. If the first argument to the AND operator (&&) is false, then the entire expression will be false. Similarly with OR (||) if the first operand in true, the entire thing is true.
This feature is useful if you want to write the code similar to:
if(a != null && a.isValid())
... Code ...
This way you are not going to get an exception if a is null.
MSDN documentation http://msdn.microsoft.com/en-us/library/2a723cdk%28v=vs.71%29.aspx
If you do it right, yes. Take a look here: http://devpinoy.org/blogs/nocampo/archive/2007/09/28/short-circuit-evaluation-in-c-and-vb-net.aspx
EDIT: To clarify; C# yes, VB.NET if you use the right keywords.
So my problem is that i am getting an invalid argument error in this section of code. What it is meant to do is take a hand of cards and get the sum of their total value. Then if the value is greater than 21 it checks to see if any of the cards in the hand is an ace(or the type is == ace and it's card totalVal == 11) now my problem is the statement i have written for this will run regardless of if there is an ace in the hand or not and throws an error.
I was wondering if there is any other way i can write the statement below in order to get this to run correctly?
public int HandTotal()
{
int total = CurrentCards.Sum(n => n.Total);
**while ( total > 21 && CurrentCards.First(n => n.Type == 13 && n.Total == 11) !=null)**
{
CurrentCards.First(n => n.Type == 13).Total = 1;
total = CurrentCards.Sum(n => n.Total);
return total;
}
return total;
}
i've tried several different things including changing the != null into > 0 however that throws an invalid argument error saying that > cannot be used with this statement. Is there any other way that i can determine if CurrentCards.First(n => n.Type == 13 && n.Total == 11) is true or false?
Any help or suggestions are greatly appreciated.
Thank You
Instead of First, use Any with the predicate.
while(total > 21 && CurrentCards.Any(n => n.Type == 13 && n.Total == 11))
The First method throws an exception if there are no matching element.
You need to call FirstOrDefault, which can return null.
You should try using FirstOrDefault instead of First.First will throw an error if no elements a returned.
Also check that CurrentCards is not empty. Both First and FirstOrDefault will give an ArguementNullException if the IEnumumerable is empty.
i found a sample code where lambda was used the code as follows
var sumOfgreaterThanSeven = numbers.Sum(n => n > 7 ? n : 0);
but the above code can be written as
var sumOfgreaterThanSeven = numbers.Sum(n > 7 ? n : 0);
so why user write lambda. please help me to understand why user write lambda here.
also tell me what is the advantage of lambda. thanks
The lambda is because you want to evaluate the conditional expression per item n. The version you added (Sum(n > 7 ? n : 0)) can't work - n isn't defined anywhere (the compiler message should be "The name 'n' does not exist in the current context").
The lambda can be read as:
given a term n, if n is greater than 7 return n, else return 0
and then sum over that logic.
Re the advantage - firstly, convenience - but also composition. For example, with LINQ-to-SQL I would absolutely expect that to issue something like:
select sum(case when row.col > 7 then row.col else 0 end)
from sometable row
of course, it might be better to use:
var sumOfgreaterThanSeven = numbers.Where(n => n > 7).Sum();
which would map to
select sum(row.col)
from sometable row
where row.col > 7
which might hit an index more accurately
You need to think of Lambda Expressions as methods.
n => n > 7 ? n : 0
Can in fact be written as
(n) => {
if(n > 7)
return n;
else
return 0;
}
Lambda expression will be converted to an anonymous method and an instance of Func<> will be created from it.
UPDATE
As Marc pointed out, this conversion to anonymous method and instance of Func<> or Action does not always happen -as rightly pointed out in Linq-to-sql. ... - but here it does, hence I pointed out the underlying.
When you write a lambda you are calling a method or evaluating an expression. The left side of the => is a set of parameters passed into the method/expression on the right side.
IEnumerableThing.Where(a => DoSomeStuff(a))
It's like writing this:
foreach (var a in IEnumerableThing)
{
DoSomeStuff(a);
}
In the case of the Sum() method you are really doing something like this:
int mysum = 0;
foreach (var n in whatever)
{
if (n > 7) { mysum += n; }
}