1

I am woking with an ASP.NET project which use LinQ to EF to communicate with SQL Server. My project is a shopping cart project, it contains some tables:

Customer(Id, Name, Address, JoinDate, ExpireDate)

I want to write a linq expression to select Id, Name, Address, JoinDate, ExpireDate and Period

The period field is ExpireDate-JoinDate. I searched in stackoverflow about this problem, there is a way to do substract is use DbFuntions.DiffDate, but the DiffDate return int value but i want timespan value.

I tried to convert the returned int value by DbFuntions.DiffDate to TimeSpan using following code:

var customers = from s in _db.Customers select new {s.Id, s.Name, s.Address, s.JoinDate, s.ExpireDate, Period = TimeSpan.FromDays(DbFunctions.DateDiff(s.ExpireDate, s.JoinDate))};

It result error:

LINQ to Entities does not recognize the method 'System.TimeSpan FromDays(Double)' method, and this method cannot be translated into a store expression.

How to resolve this?

1 Answers1

0

If you want to recieve a TimeSpan value, you should simple subtract the two dates, without using any additional methods, like this:

var customers = from s in _db.Customers 
            select new 
            {
                s.Id, 
                s.Name, 
                s.Address, 
                s.JoinDate, 
                s.ExpireDate, 
                Period = s.ExpireDate - s.JoinDate
            };
Tanya Petkova
  • 155
  • 1
  • 1
  • 7
  • It doesn't work. It will result error: > DbArithmeticExpression arguments must have a numeric common type. – Phung Tien Trieu Apr 26 '16 at 09:12
  • Check [LINQ to Entities for subtracting 2 dates](http://stackoverflow.com/questions/570858/linq-to-entities-for-subtracting-2-dates) and [DbArithmeticExpression arguments must have a numeric common type](http://stackoverflow.com/questions/9820401/dbarithmeticexpression-arguments-must-have-a-numeric-common-type) – Tanya Petkova Apr 26 '16 at 09:20