2011-11-29 39 views
1

就我个人而言,我知道Linq足够危险。Linq-to-date在数据库中的日期值是字符串

  • 手头的任务是;我需要查询DAL并返回基于日期范围的对象列表。听起来很简单,但日期是一个字符串,出于某种原因它需要保持一个字符串。

前段时间我花了一些时间,并得到一个解决方案的工作,但我遍历一个对象列表,并选择单个记录一次一个,这是badddd!如果日期范围超过了几天,它的速度就会变慢,我不喜欢它,甚至我还在这里为了做迭代查询而破坏了一些高级开发人员,所以我绝对不想成为一个伪君子。

下面是蹩脚的迭代方式...每个日期钉住数据库,我讨厌这样做。
- 这工作

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); 
} 

这是我在试图让我的查询在一个DB调用工作
尝试 - 这不工作...但

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; 

我得到的错误如下:
enter image description here

我明白为什么会出现错误,但我不知道适当的LINQ代码能够达到我想要做的。任何帮助将不胜感激。

回答

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; 
相关问题