4

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 / Mc Enroe
  • 4 / Stef / Doe

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

  • John Doe > get all contacts having the firstname John and the lastname Doe
  • John > get all contacts having the first name John
  • Doe > get all contacts having the last name Doe
  • ...

I tried to add a NotMapped element to my class and perform my search on this (full) name but LINQ query does not work with NotMapped elements.

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

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

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

Any idea?

Thanks.

Bronzato
  • 9,438
  • 29
  • 120
  • 212
  • Instead of computing the value in code, what about using a computed column in the database? http://stackoverflow.com/questions/6944904/how-should-i-access-a-computed-column-in-entity-framework-code-first has some info on that, if you read through everything. You might be able to query on the computed column at that point (never tired so I don't know 100% for sure) –  Jul 17 '15 at 15:29

1 Answers1

2

I think you don't need to create a not mapped 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 String.Concact method is supported by EF.

ocuenca
  • 38,548
  • 11
  • 89
  • 102