string.IsNullOrEmpty + Entity Framework 5

.net c# entity-framework linq-to-sql

Question

It's been a while since I've used Entity Framework, and I'm jumping back in with EF 5, but wouldn't this query:

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

be the same as:

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

When I run the LINQ to SQL code, I get the following error:

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.

Am I completely missing something here? I thought I could use string.IsNullOrEmpty with LINQ to SQL.

1
3
12/19/2012 7:18:33 PM

Accepted Answer

Replace string.Empty with "". Sadly, EF does not support string.Empty.

EF LINQ support is very bad in general. Always be aware of this problem. It is a common cause of grief with EF.

LINQ to SQL does not have problems with common language idioms.

Btw, you can rewrite this much more nicely: c.Address.Line1 ?? "".

7
12/19/2012 7:18:50 PM

Popular Answer

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

is being translated into

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

All you're doing, is setting a string value to "" if it's null or "" already.

You should try to just use Line1 = c.Address.Line1



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow