就个人而言,我知道Linq足够危险。
前段时间我花了一些时间来解决这个问题,但我正在迭代一个对象列表并按日期一个一个地选择单个记录,这是坏事!如果日期范围超过几天它很慢并且我不喜欢它,我甚至在这里破坏了一些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代码能够实现我想要做的事情。任何帮助将不胜感激。
答案 0 :(得分:0)
x.TransplantDate
成为我的Linq查询中的仅日期字符串,E.G。 10/15/2011
where sdates.Contains(EntityFunctions.TruncateTime(Convert.ToDateTime(x.TransplantDate)).ToString())
原来它在数据库中已经是正确的格式,如果我将其简化为只有
where sdates.Contains(x.TransplantDate)
它有效。我没有收到任何记录的原因是因为我测试的日期范围没有那些特定日期的任何数据...... UGHH。
总而言之,这最终工作得很好。如果有人做了类似的事情,也许你可以从这个例子中学习。
DateTime start = Convert.ToDateTime(RecipientSearch.TransplantSearchStartDate);
DateTime end = Convert.ToDateTime(RecipientSearch.TransplantSearchEndDate);
List<string> sdates = new List<string>();
while (start <= end)
{
string sStart = Convert.ToDateTime(start).ToString(ResourceFormatting.DateOnly);
sdates.Add(sStart);
start = start.AddDays(1);
}
selectQuery =
(ObjectQuery<DAL.Recipients>)
from x in entities.Recipients
where sdates.Contains(x.TransplantDate)
select x;