2017-06-26 86 views
0

我的DateTimeOffset列在我的表,当我通过LINQ查询获取从该表数据,并在我的选择使用转换的DateTimeOffset为DateTime在LINQ查询

(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是不支持的实体

是否有可能的DateTimeOffset转换为DateTime,而在查询中获取数据? 我没有在DbFunctions中看到任何函数。 我一定要取得与的DateTimeOffset数据做:

data.StartDate = data.StartDate.DateTime 

必须有simplier解决

+1

不知道是否有更好的办法,但理论上你可以选择成为一个匿名对象,做了'ToList'(强制获取结果的),然后做选择你在那里,你的调用DateTime将在LINQ中的对象,而不是LINQ到实体。 – Chris

回答

0

试试这个代码:

(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 
    } 
+0

这是不可能的,顺便说起来更好做StartDate = c.StartDate?.DateTime – kriss

1

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

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 
    });