Error when calculating date difference in Entity with Linq to Entities

Asked

Viewed 695 times

3

Before I was like this my expression:

var resultado = db.T_CRM_StatusPDV
                              .Join(db.T_PDV, t1 => t1.DE_Cnpj, t2 => t2.CNPJ, (t1, t2) => new { t1, t2})
                              .Where(dt => (TimeSpan)((dt.t1.DT_TransacaoV - DateTime.Now)).TotalDays > 45
                                     && dt.t2.DataCadastro >= dataInicio && dt.t1.DT_ControleV >= dataControle)
                              .Select(i => new { i.t1.DE_Cnpj }).ToList();

It made that mistake:

DbArithmeticExpression arguments must have a numeric common type.

I changed it to that expression:

var resultado = db.T_CRM_StatusPDV
                              .Join(db.T_PDV, t1 => t1.DE_Cnpj, t2 => t2.CNPJ, (t1, t2) => new { t1, t2})
                              .Where(dt => EntityFunctions.DiffHours(dt.t1.DT_TransacaoV,DateTime.Now) > 45 
                                     && dt.t2.DataCadastro >= dataInicio && dt.t1.DT_ControleV >= dataControle)
                              .Select(i => new { i.t1.DE_Cnpj }).ToList();

And now I’ve made that mistake:

LINQ to Entities does not recognize the method 'System.Nullable`1[System.Int32] DiffHours(System.Nullable`1[System.DateTime], System.Nullable`1[System.DateTime])' method, and this method cannot be translated into a store expression.

How can I calculate hours in a lambda or Linq to entities expression?

  • It is not whole, it is a Datetime. This field comes straight from the BD. It is of the type Datetime with certainty. In fact, Morrison, in an example in another post, we did a cast for Timespan

  • Yes, I’m testing something else to answer again.

1 answer

1


For the first mistake, change:

.Where(dt => (TimeSpan)((dt.t1.DT_TransacaoV - DateTime.Now)).TotalDays > 45

For:

.Where(dt => DbFunctions.DiffDays(dt.t1.DT_TransacaoV, DateTime.Now) > 45

On the second, try changing EntityFunctions for DbFunctions.

  • I’ll try both and put the result here.

  • Both solutions, are giving this error: Dbarithmeticexpression Arguments must have a Numeric common type. I will try with Dbfunctions

  • Dbfunctions worked. I think that’s the way. My list came up empty, I’m gonna check some records and see why, but by my question, it’s okay. If you want to change the response to Dbfunctions, then mark as solved.

  • @pnet edited. Let’s try something else.

Browser other questions tagged

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