我是Linq的新手,以下查询一直返回“无法识别System.DateTime”错误。我尝试过Parse和Convert,但都没有用。这是我的疑问:
mrcEntities context = GetContext();
var query = from c in context.tblClients
where (c.FirstName != null || c.LastName != null)
&& c.EligibilityDate >= DateTime.Parse("10/01/2011")
&& c.EligibilityDate <= DateTime.Parse("04/30/2012")
orderby c.ClientID
select new
{
ClientID = c.ClientID,
FirstName = c.FirstName,
LastName = c.LastName,
MiddleName = c.MidName,
SSN = c.SSN,
DOB = c.DOB,
Sex = c.Gender,
Ethnic = c.EthnicCode
};
clientRowCnt = query.Count();
任何帮助都将不胜感激。
答案 0 :(得分:5)
这是因为EF无法将DateTime.Parse转换为商店中可用的功能。如果您将调用的结果替换为DateTime.Parse()并在查询中使用这些变量,它应该可以正常工作。
var from = DateTime.Parse("10/01/2011");
var to = DateTime.Parse("04/30/2012");
var query = from c in context.tblClients
where (c.FirstName != null || c.LastName != null)
&& c.EligibilityDate >= from
&& c.EligibilityDate <= to
orderby c.ClientID
select new
{
ClientID = c.ClientID,
FirstName = c.FirstName,
LastName = c.LastName,
MiddleName = c.MidName,
SSN = c.SSN,
DOB = c.DOB,
Sex = c.Gender,
Ethnic = c.EthnicCode
};
clientRowCnt = query.Count();
答案 1 :(得分:2)
只需解析查询之外的日期即可。或者使用构造函数来创建日期,甚至不用解析它(你知道它们已经看到了值。
DateTime start = DateTime.Parse("10/01/2011");
DateTime emd = DateTime.Parse(04/30/2012);
var query = from c.....
或使用:
DateTime start = new DateTime(2011, 10, 01);
DateTime end = new DateTime(2012, 04, 30);
var query = from c.....
您还可以安全地解析查询的投影部分中的字符串,因为在检索数据后该部分在客户端执行。所以
var query = from c...
select
new {
EligibilityDate = Datetime.Parse(c.EligibilityDate)
}
只有当您需要将其作为DateTime值提供时,才会在选择条件中需要解析后的值。
到目前为止,更好的解决方案是修复数据库模式,甚至只是将计算列添加到现有模式中,该模式在服务器上进行解析并公开正确的Typed列。