6

Does anyone know if its possible to create a new property on an existing Entity Type which is based on 2 other properties concatenated together?

E.g. My Person Entity Type has these fields "ID", "Forename", "Surname", "DOB"

I want to create a new field called "Fullname" which is

Forenames + " " + Surname

So i end up with "ID", "Forename", "Surname", "DOB", "Fullname".

I know i can do this using Linq programmatically i.e.

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 calling something like

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

However i'd really like to use Linq to Entities to do this work for me at the Conceptual Model level.

Jeffrey L Whitledge
  • 58,241
  • 9
  • 71
  • 99
CraftyFella
  • 7,520
  • 7
  • 47
  • 61

4 Answers4

4

Not yet, but maybe soon. First, note that your suggested query will not work at all in LINQ to Entities, with or without the property, because, at present, it doesn't support Contains. The new version of the Entity Framework in .NET 4.0, however, is supposed to support custom methods in LINQ to Entities queries. You can see a video about this from PDC. Essentially, you have to write the custom method twice; once in code, and once on your database (e.g., in a calculated field). See the video for more information.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
3

For anyone happening in to read this so many years after the question has been answered:

There is a more up to date and more DRY compliant answer here: Using a partial class property inside LINQ statement

Community
  • 1
  • 1
Juliano
  • 2,402
  • 1
  • 20
  • 22
2

The reason Contains "works" for you is because you're calling String.Contains, and not IEnumerable.Contains, as Craig thought.

0

Craig,

Sarted watching the video, then realised it's over an hour long, so will have to watch it when i have more time. Just to let you know though.. Contains seems to be working ok for me, here's the SQL that's generated by Linq to 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 a treat. Using CHARINDEX to workout if the Concatinated field contains the entered text which is the above case was "Dave".

Thanks Dave

CraftyFella
  • 7,520
  • 7
  • 47
  • 61
  • How odd. I have verified myself that it doesn't work, and here's the MSDN documentation which says the same thing: http://msdn.microsoft.com/en-us/library/bb738638.aspx – Craig Stuntz Nov 21 '08 at 13:36