在LINQ查询中将DateTimeOffset转换为DateTime [英] Convert DateTimeOffset to DateTime in LINQ query

查看:273
本文介绍了在LINQ查询中将DateTimeOffset转换为DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过linq查询从该表中获取数据并使用

I have DateTimeOffset column in my table, when I fetch data from this table by linq query and use

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

在我的Select中,出现以下异常:

in my Select, I get following exception :

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

The specified type member 'DateTime' is not supported in LINQ to Entities

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

Is it possible to convert DateTimeOffset to DateTime while fetch data in query? I do not see any function in DbFunctions for this. Do I have to fetch data with DateTimeOffset and do :

data.StartDate = data.StartDate.DateTime

必须有一个更简单的解决方案

there must be simplier solution

推荐答案

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

Since projection (i.e. Select) is the last operation in the chain, you can transfer the data to memory before performing it. This way you would not need support in 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 
    });

这篇关于在LINQ查询中将DateTimeOffset转换为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆