Time difference in Linq

Asked

Viewed 130 times

6

I am using Entity Framework, and I have a condition that has not worked very well:

.Where(x => ((DateTime.Now - (x.DataInicio.Value == null ? DateTime.Now : x.DataInicio.Value)).TotalMinutes) < x.Item.MinutosMaximo)

Types:

  • x.DataInicio.Value: DateTime?
  • ((...).TotalMinutes): Double
  • x.Item.MinutosMaximo: int

The error returned is:

Dbarithmeticexpression arguments must have a common numeric type. Cannot cast and convert to repository.

  • I just forgot to paste here... Edited question.

1 answer

7


You cannot do arithmetic operations with types DateTime when using the Entityframework.

If you are using Entity Framework 5.0 or later

You must use DbFunctions. Import the namespace System.Data.Entity and your query should look like this

.Where(x => DbFunctions.DiffMinutes(DateTime.Now, 
                                    x.DataInicio.HasValue
                                      ? x.DataInicio.Value 
                                      : DateTime.Now) < x.Item.MinutosMaximo);

If you are using an older version

You must use the class EntityFunctions. Import the namespace System.Data.Objects and your query should look like this

.Where(x => EntityFunctions.DiffMinutes(DateTime.Now, 
                                        x.DataInicio.HasValue
                                          ? x.DataInicio.Value 
                                          : DateTime.Now) < x.Item.MinutosMaximo);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.