在.Net Core应用程序中使用System.Linq我尝试将AssignedDate和DateTime.Now之间的日期差异放入ElapsedTime。
var query = from r in _context.Request
join st in _context.ServiceType on r.ServiceTypeId equals st.ServiceTypeId
join u in _context.Users on r.AssignedUserId equals u.UserId into ju
from u in ju.DefaultIfEmpty()
select new RequestDto
{
RequestId = r.RequestId,
UserId = r.UserId,
//..
AssignedUserId = r.AssignedUserId.Value,
AssignedUser = u.Name,
ElapsedTime = DateDiff(r.AssignedDate, DateTime.Now)
};
DateDiff不是有效的功能。我该如何替换它?
编辑:使用MicrosoftEntityFrameworkCore 2.0。尝试EntityFunction无效。
再次编辑:我可以在视图一侧用剃须刀使用这个:
@if (item.AssignedDate != null){@DateTime.Compare(item.AssignedDate.Value, DateTime.Now)}
但那不起作用?
答案 0 :(得分:3)
不幸的是,即使在最近的EF Core 2.0.1中,EF Core中的TimeSpan
和DateTime
操作支持仍然非常完美。
例如,自然
ElapsedTime = DateTime.Now - r.AssignedDate
for SqlServer throws SqlException
- “数据类型datetime和datetime2在减法运算符中不兼容。”。
尝试使用变量
来欺骗它var baseDate = DateTime.Now;
然后
ElapsedTime = baseDate - r.AssignedDate
导致另一个SqlException
- “操作数数据类型datetime2对于减法运算符无效。”。
我能够使用w / o错误的唯一方法是DateTime.Subtract
方法:
ElapsedTime = DateTime.Now.Subtract(r.AssignedDate)
但请注意,这会导致client evaluation。
答案 1 :(得分:0)
假设您可以更改ElapsedTime
的类型,那么:
...
ElapsedTime = (DateTime.Now - r.AssignedDate).Ticks
ElapsedTime
必须是long
类型,其区别为ticks
,当您阅读它时,您可以使用TimeSpan.FromTicks(ticksValue)
,然后您可以选择你想要的成员(小时,分钟,秒,分数......)