C# LINQ to实体无法识别方法';字符串ToString()';方法转换可为空的DateTime时
我试图从一个可为空的日期时间中获取一周中的某一天,然后加入一个日期列表 我的解决方案是首先将其转换为DateTime,但LINQtoEntities不喜欢它 列表是一个C# LINQ to实体无法识别方法';字符串ToString()';方法转换可为空的DateTime时,c#,linq,linq-to-entities,C#,Linq,Linq To Entities,我试图从一个可为空的日期时间中获取一周中的某一天,然后加入一个日期列表 我的解决方案是首先将其转换为DateTime,但LINQtoEntities不喜欢它 列表是一个IEnumerable 建议 var result = from X in model.X where X.StartDate.HasValue join item in LIST on
IEnumerable
建议
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);
weekday
返回一个int
,因此您应该有一个整数而不是字符串的列表编辑:不要使用此代码。它留在这里是为了告诉你什么是行不通的,所以你可以看到Chris的原因以及如何解决。
未经测试:
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
声明为null
字段,则应检查null值。如果在转换之前使用.ToList()
,则此操作有效。
.ToString()与许多其他扩展方法一样,不受Linq To实体的支持
简短(在某种程度上可能不准确)的原因是,上面上下文中的.ToString()被发送到Sql Server以在查询中运行。Sql Server不知道.ToString()是什么,因此当Sql Server的查询解析器尝试执行它时,它会失败
另外,仅供参考
linq to entities不支持这些Convert.Todatetime()、tryparse()…这在linq to sql中工作得很好…..并且您不能在linq to entities中加入列表如何使用
X.StartDate.Value
而不是Convert.Todatetime(X.StartDate)
?X.StartDate!=null和X.StartDate.HasValue
?问问自己:null
有什么属性@KevinDeus:这很简单,可以试着看一下。你是说isX.StartDate
为null,那么你就不能得到它的HasValue
属性了吗?如果是这样,我建议您自己使用DateTime?
实例进行尝试。我不需要运行该查询,LinqToEntities不喜欢.ToString()。不支持+1,但要小心-如果服务器的@@DATEFIRST
已被修改,则DATEPART
返回的值将更改。您还可以使用SqlFunctions.DateName
以字符串形式获取一周中的某一天。您是对的,但如果使用DateName,您必须担心文化我正在使用它,但获取的错误不受支持异常:方法'System.Nullable`1[System.Int32]是数字(System.string)'不支持转换为SQL.]在我的代码中,下一步要做什么来解决这个问题。这将“使它工作”,但您的链接对此进行了最好的解释:“缺点是当您调用.ToList()时,它将从数据库中获取所有数据,然后在主机端而不是数据库端进行转换”——这与我的目的不完全相同。
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;
var result = model.X.Where(x => x.StartDate.HasValue).ToList().Join(LIST,x => Convert.ToDateTime(x.StartDate).DayOfWeek.ToString(), item => item, (x, item) => x);