Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Entities and concatenated properties

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.

like image 998
CraftyFella Avatar asked Nov 18 '08 16:11

CraftyFella


2 Answers

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.

like image 71
Craig Stuntz Avatar answered Oct 10 '22 08:10

Craig Stuntz


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

like image 33
Juliano Avatar answered Oct 10 '22 08:10

Juliano