LINQ to SQL的特殊性 [英] LINQ to SQL Peculiarities
问题描述
我现在遇到一些特殊性与LINQ到SQL。
I'm encountering some peculiarities with LINQ to SQL.
通过一个相对简单的查询,我想选择一些字段,但格式化为字符串日期字段,这是我第一次取得这样的:
With a relatively simple query, I want to select some fields, but have the date fields formatted as strings, which I first achieved like this:
var list = dataContext.MyLists.Single(x => x.ID == myId);
var items = from i in list.MyItems
select
new
{
i.ID,
i.Sector,
i.Description,
CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "",
DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : ""
};
后来我尝试下面的查询,这是完全一样的,只是我直起查询我的DataContext,而不是在我的第一个查询的元素:
Later on I tried the following query, which is exactly the same, except I'm querying straight from my dataContext, rather than an element in my first query:
var items = from i in dataContext.MyLists
select
new
{
i.ID,
i.Sector,
i.Description,
CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "",
DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : ""
};
第一个运行正常,但第二个查询产生了:
The first one runs fine, yet the second query yields a:
的表达'...'无法转化为SQL,不能把它当作一个局部表现。的
如果删除该格式的日期的线条,它工作正常。如果我删除.HasValue检查它也工作得很好,直到有空值。
If I remove the lines that Format the date, it works fine. If I remove the .HasValue check it also works fine, until there are null values.
任何想法?
安东尼
推荐答案
我会做的SQL语句组成部分,而不做格式化,然后做在客户端的格式:
I'd do the SQL part without doing the formatting, then do the formatting on the client side:
var items = list.MyItems.Select(item => new { item.ID, item.Sector, item.Description,
item.CompleteDate, item.DueDate })
.AsEnumerable() // Don't do the next bit in the DB
.Select(item => new { item.ID, item.Sector, item.Description,
CompleteDate = FormatDate(CompleteDate),
DueDate = FormatDate(DueDate) });
static string FormatDate(DateTime? date)
{
return date.HasValue ? date.Value.ToShortDateString() : ""
}
这篇关于LINQ to SQL的特殊性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!