Combine columns in entity framework into one column with the edmx designer

5.7k Views Asked by At

I'm using EntityFramework 5 EDMX designer and would like to combine the first & last name of a person into a single field value (name, for instance) on the entity.

I thought in previous versions there was a way to do this, but I don't see anything available to do what I need to do.

Is this still possible?

3

There are 3 best solutions below

0
On

No it is not possible. You can create model defined function and use it in queries but it will still not be part of your entity. If your entity is read only you can create database view with combined column and map it instead of the table - it shows also main reason why combining columns into single property is not such easy task. Automatic concatenating during reading is easy but automatic decomposing to save correct value into correct column is hard and error prone.

If you need combined property for anything else than querying you can simply create another partial part of your entity class and add your own computed property. If you need the combined property for querying use the model defined function.

0
On

The way I do this is through a Computed Column as explained here:

How to make a computed column nullable in SQL Server

If you use a computed column you'll be able to use such a column in your LINQ queries. For example:

var users = Database.Users.Where(u => u.FullName.ToLower().Contains("string"));

You won't get errors like "not supported in LINQ to Entities" because this property is really a part of your model object. All the heavy lifting occurs on the database side.

Of course you could place a FullName property in a partial class and use it.

public string FullName 
{
    get { return string.Format("{0} {1}", FirstName, LastName); }
}

In this case, you'll have to call .ToList() first ( Database.Users.ToList(); ) to be able to use this property in LINQ queries. .ToList() will hydrate/bring all your Users to memory. This is not desirable!


You can also try the FullName property implementation that's described here: Calculated Columns in Entity Framework Code First Migrations

0
On

Unless I'm not understanding your question, I believe I've done that with a partial class that resembles something like the following:

    public partial class person
    {
        public string name { 
            get
            {
                return firstname + " " + lastname;
            }
            set{ }
        }
    }