2012-09-12 104 views
0

我有以下的LINQ to SQL:如何格式化數據值

var subscribers = (from s in dataContext.Employees 
           where s.RowType == "Edit" 
           select new SubscriberExportData 
              { 
               ID = s.ID.ToString(), 
               GroupNum = s.GroupNumber, 
               DivisionNum = s.DivisionNumber, 
               HireDate = s.HireDate != null ? Convert.ToDateTime(s.HireDate).ToShortDateString() : string.Empty, 
               EffDate = s.EffectiveDate != null ? Convert.ToDateTime(s.EffectiveDate).ToShortDateString() : string.Empty 
              } 

從本質上講,如果日期值不爲空,然後將它們轉換爲短日期格式。但我收到以下錯誤:

System.InvalidOperationException was unhandled Message=Could not translate expression 'Table(Employee).Where(s => (s.RowType == "Edit")).Select(s => new SubscriberExportData() { HireDate = IIF((s.HireDate != null), ToDateTime(Convert(s.HireDate)).ToShortDateString(), Invoke(value(System.Func`1[System.String]))), EffDate = IIF((s.EffectiveDate != null), ToDateTime(Convert(s.EffectiveDate)).ToShortDateString)' into SQL and could not treat it as a local expression. Source=System.Data.Linq

請讓我知道如何解決它。

+2

執行? –

回答

0

您可以您所使用的語言或者VB或者C#查詢分成兩個,第一個是操作該SQL理解,第二個是字符串轉換,這種轉換將在本地

var list = (from s in dataContext.Employees 
          where s.RowType == "Edit" 
          select new 
             { 
              s.ID 
              s.GroupNumber, 
              s.DivisionNumber, 
              s.HireDate 
              s.EffectiveDate 
             }).ToList(); 

var subscribers = (from s in list 
          select new SubscriberExportData 
             { 
              ID = s.ID.ToString(), 
              GroupNum = s.GroupNumber, 
              DivisionNum = s.DivisionNumber, 
              HireDate = s.HireDate != null ? Convert.ToDateTime(s.HireDate).ToShortDateString() : string.Empty, 
              EffDate = s.EffectiveDate != null ? Convert.ToDateTime(s.EffectiveDate).ToShortDateString() : string.Empty 
             }