Linq to Entities and Concatenated Properties

Does anyone know if it is possible to create a new property for an existing Entity type that is based on two other properties combined together?

eg. My Person Entity Type has the following fields: "ID", "Forename", "Surname", "DOB"

I want to create a new field called "Full Name", which

Forenames + " " + Surname 

So, I have "ID", "Forename", "Surname", "DOB", "Fullname".

I know I can do this with Linq programmatically.

 var results = from p in db.People select new { ID = p.ID, Forename = p.Forename, Surname = p.Surname, DOB = p.DOB, Fullname = p.Forename+ " " + p.Surname }; 

Then call something like

 var resultsAfterConcat = from q in results where q.Fullname.Contains(value) select q; 

However, I would really like to use Linq for Entities to do this work for me at the conceptual model level.

+6
c # linq linq-to-entities
source share
4 answers

Not yet, but maybe soon. First, note that your proposed query will not work at all in LINQ to Entities, with or without a property, because it currently does not support Contains. However, the new version of Entity Framework in .NET 4.0 must support custom methods in LINQ to Entities queries. You can see a video about this from the PDC . Essentially, you have to write your own method twice; once in code and once in your database (for example, in a computed field). Watch the video for more information.

+4
source share

For those who are going to read this many years after answering the question:

There is a more relevant and more DRY-compatible answer: Using a partial class property inside a LINQ statement

+3
source share

The reason Contains "works" for you because you are calling String.Contains, not IEnumerable.Contains, as Craig thought.

+2
source share

Craig

Sarted watched the video and then understood it for an hour, so I’ll have to watch it when I have more time. Just to let you know that .. Contains seems to work fine for me, here is the SQL that Linq generates for Entities:

 SELECT 1 AS [C1], [Extent1].[PeopleID] AS [PeopleID], [Extent1].[Forenames] AS [Forenames], [Extent1].[Surname] AS [Surname] FROM [dbo].[People] AS [Extent1] WHERE (CHARINDEX(N'Dave', [Extent1].[Forenames] + N' ' + [Extent1].[Surname])) > 0 

It seems to work. Using CHARINDEX for training, if the Concatinated field contains the entered text, which is the above case, was " Dave ".

Thanks Dave

0
source share

All Articles