2012-12-19 111 views
1

它是因为我已经使用实体框架的同时,和我跳回到与EF 5,但不会此查询:string.IsNullOrEmpty +实体框架5

SELECT 
    c.OrganizationName as CompanyName, 
    c.OrganizationKey as CompanyId, 
    ISNULL(a.Line1, '') as Line1, 
    ISNULL(a.Line2, '') as Line2, 
    a._CityStateZip as CityStateZip 
FROM Organizations c 
JOIN Addresses a ON c.AddressKey = a.AddressKey 
WHERE c.OrganizationName LIKE @term + '%' 
AND c.IsSuspended = 0 
AND c.IsActive = 1 

相同如:

var results = (from c in adms.Organizations 
       where c.OrganizationName.StartsWith(term) 
       where !c.IsSuspended 
       where c.IsActive 
       select new 
       { 
       CompanyName = c.OrganizationName, 
       CompanyId = c.OrganizationKey, 
       Line1 = (string.IsNullOrEmpty(c.Address.Line1) ? string.Empty : c.Address.Line1), 
       Line2 = (string.IsNullOrEmpty(c.Address.Line2) ? string.Empty : c.Address.Line2), 
       CityStateZip = c.Address._CityStateZip 
       }).ToList(); 

当我运行的LINQ to SQL代码,我得到以下错误:

Could not translate expression 
'Table(Organization).Where(c => c.OrganizationName 
.StartsWith(Invoke(value(System.Func`1[System.String])))) 
.Where(c => Not(c.IsSuspended)) 
.Where(c => c.IsActive) 
.Select(c => new <>f__AnonymousType2`5(
CompanyName = c.OrganizationName, 
CompanyId = c.OrganizationKey, 
Line1 = IIF(IsNullOrEmpty(c.Address.Line1), 
Invoke(value(System.Func`1[System.String])), c.Address.Line1), 
Line2 = IIF(IsNullOrEmpty(c.Address.Line2), 
Invoke(value(System.Func`1[System.String])), c.Address.Line2), 
CityStateZip = c.Address._CityStateZip))' 
into SQL and could not treat it as a local expression. 

难道我完全失去了一些东西,他回覆?我以为我可以使用LINQ to SQL的string.IsNullOrEmpty。

+0

EF LINQ支持只是很伤心...... LINQ to SQL支持这个(还有更多)。 – usr

回答

6

更换string.Empty""。不幸的是,EF不支持string.Empty

EF LINQ支持一般很糟糕。始终注意这个问题。这是EF造成悲伤的常见原因。

LINQ to SQL在通用语言习语方面没有问题。

顺便说一句,你可以更好地改写这个好得多c.Address.Line1 ?? ""

+1

这正是我需要的。也感谢提示使用c.Address.Line1 ?? “”.... ??完全滑了我的脑海! –

+0

谢谢..你救我一天! –

+1

可能是这个回答太旧了。但是用EF6,它也支持string.Empty。 –

1
(string.IsNullOrEmpty(c.Address.Line1) ? string.Empty : c.Address.Line1) 

被翻译成

IIF(IsNullOrEmpty(c.Address.Line1), Invoke(value(System.Func`1[System.String])), c.Address.Line1) 

所有你正在做的,是设置一个字符串值""如果它是空或""了。

你应该尽量只使用Line1 = c.Address.Line1

+0

Line1 =如果Line1为null,则c.Address.Line1返回值null。这就是为什么我想使用string.IsNullOrEmpty。 –