Mr.*_*yyy 3 c# linq datetime asp.net-web-api2
用户在URL中输入两个参数,即开始日期和结束日期,并以格式输入yyyyMMddhhmm字符串.我正在尝试将这些字符串转换为日期,以便我可以查询我的数据库.
[ResponseType(typeof(Detail))]
public IHttpActionResult GetDetail(string StartDate, string EndDate)
{
DateTime StartDateTime;
DateTime EndDateTime;
StartDateTime = new DateTime();
EndDateTime = new DateTime();
StartDateTime = DateTime.ParseExact(StartDate, "yyyyMMddhhmm", null);
EndDateTime = DateTime.ParseExact(EndDate, "yyyyMMddhhmm", null);
var detail = from a in db.Details where (a.callDate >= StartDateTime && a.callDate <= EndDateTime) select a;
var Response = new DetailResponse() { status = true, calls = detail };
return Ok(response);
}
Run Code Online (Sandbox Code Playgroud)
但是我得到的错误> =不能在datetime和字符串中使用.
编辑: 为了答案之一,我包括一个我用来显示数据的模型类.
DetailResponse.cs
public class DetailResponse
{
public bool status { get; set; }
public string statusMessage { get; set; }
public IQueryable<Detail> calls { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
可能会发生这种情况,因为它callDate是一个字符串.因此,您无法将字符串与日期时间进行比较.这个问题的解决方案是使用相同的类型.那就是说我会转换a.callDate为DateTime.
但是,我认为更改callDate数据库级别的数据类型会更好.毫无疑问,这是个人意见.所以你不必遵循它.这样做您的代码不需要任何更改.
现在,就代码而言,我上面提出的解决方案如下:
var allDetails = db.Details.AsEnumerable();
var details = from detail in details
let callDate = DateTime.ParseExact(detail.callDate, "yyyyMMddhhmm", null)
where callDate >= StartDateTime
&& callDate <= EndDateTime
select detail;
Run Code Online (Sandbox Code Playgroud)
更新
正如我们在评论中总结的那样,我们不得不调用AsEnumerable,以便上述查询工作.为什么需要这个?
借用Jon Skeet从Reimplementing Linq到Objects的话:第36部分 - AsEnumerable
现在,它不是完全少见要在数据库中执行查询的某些方面,然后在.NET多一点的操作 - 特别是如果有到SQL(或任何供应商你,你基本上不能在LINQ实现这些方面的使用).例如,您可能希望构建一个特定的内存表示形式,该表示形式并非真正适用于提供者的模型.
将DateTime.ParseExact不能在一个数据库的方法正确地翻译.
| 归档时间: |
|
| 查看次数: |
7254 次 |
| 最近记录: |