我正试图从Nullable DateTime获取星期几,然后加入一系列日期。
我的解决方案是首先将其转换为DateTime,但Linq to Entities不喜欢它。
LIST是IEnumerable<string>
建议?
var result = from X in model.X
where X.StartDate.HasValue
join item in LIST on
Convert.ToDateTime(X.StartDate).DayOfWeek.ToString() equals item
select X;
转换为方法链无济于事:
var result = model.X.Where(x => x.StartDate.HasValue).Join(LIST,x => Convert.ToDateTime(x.StartDate).DayOfWeek.ToString(), item => item, (x, item) => x);
答案 0 :(得分:2)
var result = from X in model.X
where X.StartDate.HasValue &&
List.Contains(SqlFunctions.DatePart("weekday", X.StartDate))
select X;
weekday
返回int
,因此你应该有一个整数列表而不是字符串
答案 1 :(得分:1)
如果您在转换之前使用.ToList()
,这将有效。
Entity 4.0 Casting Value As DateTime
var result = model.X.Where(x => x.StartDate.HasValue).ToList().Join(LIST,x => Convert.ToDateTime(x.StartDate).DayOfWeek.ToString(), item => item, (x, item) => x);
答案 2 :(得分:1)
。Linq-To-Entities不支持.ToString(),以及许多其他扩展方法。
短(并且可能在某种程度上不准确)的原因是上面的上下文中的.ToString()被发送到Sql Server以在查询中运行。 Sql Server不知道.ToString()是什么,因此当Sql Server的查询解析器尝试执行它时它会失败。
另外,仅供参考
答案 3 :(得分:0)
未测试:
var result = from X in model.X
where ((X.StartDate != null) && X.StartDate.HasValue)
join item in LIST on
Convert.ToDateTime(X.StartDate).DayOfWeek.ToString() equals item
select X;
如果您已将StartDate
声明为Nullable
字段,则应检查是否存在空值。