【问题标题】:Convert DateTimeOffset to DateTime in LINQ query在 LINQ 查询中将 DateTimeOffset 转换为 DateTime
【发布时间】:2017-06-26 10:11:08
【问题描述】:

当我通过 linq 查询从该表中获取数据并使用时,我的表中有 DateTimeOffset 列

 (from c in this.dbContext.SomeTable
  where c.Id == someId
  select new SomeModel()
  {
       Id = c.Id,
       Name = c.Name,
       StartDate = c.StartDate.DateTime // <-- problematic line  
  }

在我的选择中,我得到以下异常:

LINQ to Entities 不支持指定的类型成员“DateTime”

在查询中获取数据时是否可以将 DateTimeOffset 转换为 DateTime? 我在 DbFunctions 中没有看到任何功能。 我是否必须使用 DateTimeOffset 获取数据并执行:

data.StartDate = data.StartDate.DateTime

必须有更简单的解决方案

【问题讨论】:

  • 不确定是否有更好的方法,但理论上您可以选择一个匿名对象,执行ToList(强制获取结果),然后在您那里进行选择这表明您对 DateTime 的调用将在 LINQ to objects 而不是 LINQ to Entities 中。

标签: c# linq


【解决方案1】:

由于投影(即Select)是链中的最后一个操作,您可以在执行之前将数据传输到内存。这样您就不需要 LINQ to Entities 中的支持:

res = this.dbContext.SomeTable
    .Where(c => c.Id == someId)
    .AsEnumerable() // The following "Select" run in memory
    .Select(c => new SomeModel {
        Id = c.Id
    ,   Name = c.Name
    ,   StartDate = c.StartDate.DateTime // No problem here 
    });

【讨论】:

  • 如果它不是链中的最后一个操作怎么办? Telerik MVC DataSourceRequest(过滤器)仅适用于视图模型 afaik。
【解决方案2】:

试试这个代码:

(from c in this.dbContext.SomeTable
  where c.Id == someId
  select new SomeModel()
  {
       Id = c.Id,
       Name = c.Name,
       StartDate = c.StartDate!=null ? c.StartDate.DateTime:null // <-- Check null
  }

【讨论】:

  • 不可能,顺便说一句,StartDate = c.StartDate?.DateTime 更好
猜你喜欢
  • 2012-12-05
  • 2013-07-25
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-24
  • 2011-06-24
  • 2020-10-07
相关资源
最近更新 更多