我知道有很多类似的问题,但我找不到他们的答案。
我的功能是这样的:
public static Expression<Func<DateTime, DateTime?, DateTimeOffset>> GetDTOFromLocalAndUTC(DateTime localTime, DateTime? utcTime)
{
int documentDateOffset = 0;
DateTimeOffset result;
if (utcTime.HasValue)
{
documentDateOffset = ((TimeSpan)(localTime - utcTime.Value)).Hours;
}
result = new DateTimeOffset(localTime, TimeSpan.FromHours(documentDateOffset));
return (a, b) => result;
}
我的linq查询是这样的:
var q = from a in context.MyDBEntity
where {some condition}
select new MyDomainClass
{
DocumentDateInDateTimeOffsetFormat = GetDTOFromLocalAndUTC(a.LocalDocumentDate, a.UTCDocumentDate)
};
但它会给出转换错误。
答案 0 :(得分:2)
你不能这样做......
public static DateTimeOffset GetDTOFromLocalAndUTC(DateTime localTime, DateTime? utcTime)
{
int documentDateOffset = 0;
DateTimeOffset result;
if (utcTime.HasValue)
{
documentDateOffset = ((TimeSpan)(localTime - utcTime.Value)).Hours;
}
result = new DateTimeOffset(localTime, TimeSpan.FromHours(documentDateOffset));
return result;
}
然后
var q = (from a in context.MyDBEntity
where {some condition}
select new
{
a.LocalDocumentDate,
a.UTCDocumentDate
})
.AsEnumerable()
.Select(a => new MyDomainClass
{
DocumentDateInDateTimeOffsetFormat = GetDTOFromLocalAndUTC(a.LocalDocumentDate, a.UTCDocumentDate)
});
首先,您选择所需的两个字段,然后选择本地(AsEnumerable()
)来调用您的函数。