The specified type member is not supported in LINQ to Entities occurs when a new property is added in the partial class

c# entity-framework-6 linq

Question

I'm having an entity framework's EDMX generated class having two properties

public partial class Contact : EntityBase
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I require additional property that should return FullName by joining FirstName and LastName. So I created a partial class for this.

public partial class Contact
{
    public string FullName
    {
        get { return string.Format("{0}{1}", FirstName, !string.IsNullOrEmpty(LastName) ? " " + LastName : String.Empty); }
    }
}

Now, I created a LINQ expression to search records matching "Steeve John" against FullName.

Expression<Func<Contact, bool>> cntExpression = p => 
                p.FullName.ToLower().Trim().Contains("Steeve John");

I passed this expression to the business logic to retrieve an IQueryable instance.

            IQueryable<Contact> qryContact = _cntMgr.GetFiltered(cntExpression);

The code fails at this line of code:

            var contactLeads = qryContact.Select(
                  s => s.Leads.Where(a => a.IsActive).GroupBy(a => a.ContactId).Select(a => a.FirstOrDefault())).ToList();

and the error that I get is this:

The specified type member 'FullName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Please help me in fixing this issue.

Thanks in advance.

1
0
8/31/2015 11:59:36 AM

Accepted Answer

Linq to entities does not know about string.Format which you used in FullName. You could try something like that:

Expression<Func<Contact, bool>> cntExpression = p => 
(p.FirstName + " " + p.LastName).ToLower().Trim().Contains("Steeve John");

or

Expression<Func<Contact, bool>> cntExpression = p => 
(p.FirstName == "Steeve" && p.LastName == "John");

You could also get Leads as a list first. Then your original code should work as well:

s.Leads.ToList().Where [...]
0
8/31/2015 11:55:01 AM

Popular Answer

Any custom properties cannot be used in query expressions; basically that error is saying there is no "Name" (or I think this is supposed to be "FullName"? If not, where did "Name" come from) field in the database, at least BEFORE the query has ran against the database. AFTER, you can use it fine. The query is failing there because ToList() executes it against the database, and that is when the validation happens.

Query the record first, then use FullName after the call to ToList, and it will work fine.



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