【发布时间】:2011-11-29 22:25:44
【问题描述】:
就我个人而言,我知道 Linq 足够危险。
- 手头的任务是;我需要查询 DAL 并根据日期范围返回对象列表。听起来很简单,但是日期是一个字符串,并且由于某种原因它需要保留一个字符串。
前段时间我花了一些时间解决了这个问题,但我正在迭代一个对象列表,并一次按日期选择单个记录,这太糟糕了!如果日期范围超过几天,它会很慢而且我不喜欢它,而且我什至已经破坏了这里的一些 Sr 开发人员进行迭代查询,所以我绝对不想成为一个伪君子.
这是糟糕的迭代方式……每个日期都与数据库挂钩,我讨厌这样做。
- 这行得通
DateTime start = Convert.ToDateTime(RecipientSearch.TransplantSearchStartDate);
DateTime end = Convert.ToDateTime(RecipientSearch.TransplantSearchEndDate);
var tempselectQuery = selectQuery;
while (start <= end)
{
tempselectQuery = selectQuery;
string sStart = Convert.ToDateTime(start).ToString(ResourceFormatting.DateOnly);
tempselectQuery = (ObjectQuery<DAL.Recipients>)tempselectQuery.Where(item => item.TransplantDate == sStart);
if (tempselectQuery.Count() != 0) TXPlistQueryDAL.AddRange(tempselectQuery.ToList());
start = start.AddDays(1);
}
这是我试图让我的查询在一个数据库调用中工作的尝试
- 这行不通……还没有
DateTime start = Convert.ToDateTime(RecipientSearch.TransplantSearchStartDate);
DateTime end = Convert.ToDateTime(RecipientSearch.TransplantSearchEndDate);
List<string> sdates = new List<string>();
// Put my date strings in a list so I can then do a contains in my LINQ statement
// Date format is "11/29/2011"
while (start <= end)
{
string sStart = Convert.ToDateTime(start).ToString(ResourceFormatting.DateOnly);
sdates.Add(sStart);
start = start.AddDays(1);
}
// Below is where I get hung up, to do a .contains i need to pass in string, however x.TransplantDate
// includes time, so i am converting the string to a date, then using the EntityFunction to Truncate
// the time off, then i'd like to end up with a string, hence the .ToString, but, linq to entities
// thinks this is part of the sql query and bombs out... This is where I'm stumped on what to do next.
selectQuery =
(ObjectQuery<DAL.Recipients>)
from x in entities.Recipients
where sdates.Contains(EntityFunctions.TruncateTime(Convert.ToDateTime(x.TransplantDate)).ToString())
select x;
我得到的错误如下:
我理解为什么会出现错误,但我不知道正确的 LINQ 代码能够实现我想要做的事情。任何帮助将不胜感激。
【问题讨论】:
标签: asp.net linq linq-to-entities linq-to-objects