string.IsNullOrEmpty + Entity Framework 5

5

我已经有一段时间没用过Entity Framework了,现在我要使用EF 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。


EF LINQ的支持实在是令人失望...而LINQ to SQL则支持这个(以及更多)。 - usr
2个回答

10

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

总的来说,EF LINQ的支持非常差。一定要注意这个问题。这是EF常见的烦恼之一。

LINQ to SQL不会出现常见语言习惯的问题。

顺便说一句,你可以更好地重写它:c.Address.Line1 ?? ""


1
这正是我所需要的。感谢您提供使用 c.Address.Line1 ?? "" 的提示,完全忘记了! - Johnie Karr
谢谢,你帮我节省了一天的时间! - Benhar Upasana
1
也许这个答案有点旧了。但是使用EF6,它也支持string.Empty。 - Prasad Kanaparthi

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)

你所做的就是将字符串值设置为空字符串"",如果它为null或者已经是""
你应该尝试只使用Line1 = c.Address.Line1

如果Line1为null,那么c.Address.Line1将返回null。这就是为什么我想使用string.IsNullOrEmpty的原因。 - Johnie Karr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接