Time difference in Linq

5

I'm 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. Unable to cast and convert to repository.

    
asked by anonymous 27.10.2015 / 12:45

1 answer

5

You can not do arithmetic operations with types DateTime when you are using EntityFramework.

If you are using Entity Framework 5.0 or later

You should 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 should use the 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);
    
27.10.2015 / 13:19