【问题标题】:string.IsNullOrEmpty + Entity Framework 5string.IsNullOrEmpty + 实体框架 5
【发布时间】:2012-12-19 19:06:15
【问题描述】:

自从我使用 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.

我在这里完全错过了什么吗?我想我可以将 string.IsNullOrEmpty 与 LINQ to SQL 一起使用。

【问题讨论】:

  • EF LINQ 支持令人遗憾...LINQ to SQL 支持这一点(以及更多)。

标签: c# .net entity-framework linq-to-sql


【解决方案1】:

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

一般来说,EF LINQ 支持非常糟糕。始终注意这个问题。这是 EF 悲伤的常见原因。

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

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

【讨论】:

  • 这正是我所需要的。也感谢使用 c.Address.Line1 的提示? “”……??我完全忘记了!
  • 谢谢..你节省了我的 1 天!
  • 可能是这个答案太旧了。但是对于 EF6,它也支持 string.Empty。
【解决方案2】:
(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

【讨论】:

  • Line1 = c.Address.Line1 如果 Line1 为空,则返回空值。这就是我想使用 string.IsNullOrEmpty 的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
相关资源
最近更新 更多