Execute LINQ Query Without Using NotMapped Properties In EF

I have the following class:

public class Contact
{
    public int ContactID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

      

And the following data:

  • 1 / John / Doe
  • 2 / Mike / Tyson
  • 3 / John / McEnroe
  • 4 / Stef / Doe

Now I need to allow the user to search for contacts like this:

  • John Doe

    > get all contacts having first name John

    and lastnameDoe

  • John

    > get all contacts with a name John

  • Doe

    > get all contacts with a last name Doe

  • ...

I tried to add an element NotMapped

to my class and do my search on that (full) name, but the LINQ query doesn't work with the elements NotMapped

.

[NotMapped]
public string Name {
    get {
        return FirstName + " " + LastName;
    }
}

var someone = "John Doe";
requests.Where(s => s.Contact.Name.Contains(someone));

      

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

Any idea?

Thank.

+3


source to share


1 answer


I think you don't need to create a non-displayable property to achieve what you need. You can try this:

var someone = "John Doe";
var contacts=context.Contacts.Where(c => String.Concat(c.FirstName, " ", p.LastName).Contains(someone));

      



The method is String.Concact

supported by EF.

+1


source







All Articles