2011-07-08 28 views
6

私はEntityFramework 4、LINQ、およびC#を使用します。LINQ - クエリ式を使用してデータの時間差を計算する

Linqを使用しているクエリ式からGridViewに表示データが必要です。 anonymous typeとして計算する必要があります。DateTime.UtcNow - cl.DateLocked注:cl.DateLockedは、タイプDateTimeです。この2つの日付の差異の日数を知る必要があります。このクエリでは

私はエラーが表示されます。

DbArithmeticExpression arguments must have a numeric common type. 

のLINQでそれを行うにはどのように任意のアイデア? Linqが別の方法でそれを行う方法を許可していない場合は?お時間を

おかげ

var queryContentsLocked = from cl in context.CmsContentsLockedBies 
          join cnt in context.CmsContents 
          on cl.ContentId equals cnt.ContentId 
          join u in context.aspnet_Users 
          on cl.UserId equals u.UserId 
          select new 
          { 
          cl.DateLocked, 
          cnt.ContentId, 
          cnt.Title, 
          u.UserName, 
          u.UserId, 
          TimePan = DateTime.UtcNow - cl.DateLocked // Problem here!!! 
          }; 

答えて

7
var queryContentsLocked = from cl in context.CmsContentsLockedBies 
          join cnt in context.CmsContents 
          on cl.ContentId equals cnt.ContentId 
          join u in context.aspnet_Users 
          on cl.UserId equals u.UserId 
          select new 
          { 
          cl.DateLocked, 
          cnt.ContentId, 
          cnt.Title, 
          u.UserName, 
          u.UserId, 
          Days = SqlFunctions.DateDiff("day", cl.DateLocked, DateTime.UtcNow) 
          }; 
+0

ありがとう@Magnusそれは素晴らしい仕事です。 DateDiffメソッドは名前空間にあります。using System.Data.Objects.SqlClient; – GibboK

-2

これを試してみてください:

DateTime.UtcNow.Subtract(cl.DateLocked).TotalDays 
+0

エラー:\t匿名型メンバー宣言子が無効です。これは、Linqクエリ式の内部で行う必要があります。 – GibboK

2

その後、

var grandTotalWork = (from t in db.AssignmentHandymandetails 
          join ad in db.AssignmentDetails on t.assignment_detail_id equals ad.assignment_detail_id 
          where ad.assignment_id == Convert.ToInt32(Label_assignmentId.Text) 
          select new { startTime = t.started_time.Value.TimeOfDay, endTime = t.end_time.Value.TimeOfDay, TotalWorkTime = (t.started_time.Value.TimeOfDay.Duration() - t.end_time.Value.TimeOfDay.Duration()).Duration()}); 

あなたが

を希望するGridViewで結果をバインドすることができます任意のSqlFunctionを使用しません
+1

提案をいただきありがとうございます。本当にありがとうございます。 – Dipen

+0

cool、thanks :-) – kleopatra

関連する問題