简体   繁体   中英

how can Calculate difference between two dates (number of days) using linq to entities?

var worker = from w in db.Distributions
                     join d in db.Distributions on w.WorkerId equals d.WorkerId
                     join p in db.Products on d.ProductId equals p.ProductId

                     select new DataBindingProjection
                     {
                         Date = d.DateTime,
                         ProductName = d.Product.ProductName,
                         DistributedPiece = d.Piece,
                         HowManyDays = db.Distributions.Where(r => DbFunctions.TruncateTime(r.DateTime) == DateTime.Now.Date)
                     };

        dataGridView1.DataSource = worker.ToList();

//I'm tired for this try various way but still now i face this error..System.NotSupportedException: 'The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.' **Where HowManyDays is string type variable. How can solve it? I want to see:Example - "10 days ago" this type answer.

Try the following solution to get the date difference of two dates:

var days = from items in Vals
            select new
            {
                days = items.maxdate - items.mindate
            };

foreach (var day in days)
{
    Console.WriteLine(day.days.TotalDays);
}

According to that error message, linq thinks that Date property needs to be converted to an SQL statement.

Try declaring DateTime.Now.Date earlier on a separate line before the linq statement, like var nowDate = DateTime.Now.Date , then reference nowDate in the linq statement instead of DateTime.Now.Date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM