I had a couple people ask me about calculated properties / columns in Entity Framework this week. The question was, is there a way to specify a property in my C# class that is the result of some calculation involving 2 properties of the same class. For example, in my database, I store a FirstName and a LastName column and I would like a FullName property that is computed from the FirstName and LastName columns. My initial answer was:
public string FullName
{
get { return string.Format("{0} {1}", FirstName, LastName); }
}
Of course, this works fine, but this does not give us the ability to write queries using the FullName property. For example, this query:
var users = context.Users.Where(u => u.FullName.Contains("anan"));
Would result in the following NotSupportedException:
The specified type member ‘FullName’ is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
It turns out there is a way to support this type of behavior with Entity Framework Code First Migrations by making use of Computed Columns in SQL Server. While there is no native support for computed columns in Code First Migrations, we can manually configure our migration to use computed columns.
Let’s start by defining our C# classes and DbContext:
public class UserProfile {
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string FullName { get; private set; }
}
public class UserContext : DbContext {
public DbSet<UserProfile> Users { get; set; }
}
The DatabaseGenerated attribute is needed on our FullName property. This is a hint to let Entity Framework Code First know that the database will be computing this property for us.
Next, we need to run 2 commands in the Package Manager Console. First, run Enable-Migrations to enable Code First Migrations for the UserContext. Next, run Add-Migration Initial to create an initial migration. This will create a migration that creates the UserProfile table with 3 columns: FirstName, LastName, and FullName. This is where we need to make a small change. Instead of allowing Code First Migrations to create the FullName property, we will manually add that column as a computed column.
public partial class Initial : DbMigration {
public override void Up() {
CreateTable("dbo.UserProfiles",
c => new {
Id = c.Int(nullable: false, identity: true),
FirstName = c.String(), LastName = c.String(),
// FullName = c.String(),
})
.PrimaryKey(t => t.Id);
Sql("ALTER TABLE dbo.UserProfiles ADD FullName AS FirstName + ' ' + LastName");
}
public override void Down() {
DropTable("dbo.UserProfiles");
}
}
Finally, run the Update-Database command. Now we can query for Users using the FullName property and that query will be executed on the database server. However, we encounter another potential problem. Since the FullName property is calculated by the database, it will get out of sync on the object side as soon as we make a change to the FirstName or LastName property.
Luckily, we can have the best of both worlds here by also adding the calculation back to the getter on the FullName property:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string FullName {
get { return FirstName + " " + LastName; }
private
set {
// Just need this here to trick EF
}
}
Now we can both query for Users using the FullName property and we also won’t need to worry about the FullName property being out of sync with the FirstName and LastName properties. When we run this code:
using (UserContext context = new UserContext()) {
UserProfile userProfile =
new UserProfile { FirstName = "Chanandler", LastName = "Bong" };
Console.WriteLine("Before saving: " + userProfile.FullName);
context.Users.Add(userProfile);
context.SaveChanges();
Console.WriteLine("After saving: " + userProfile.FullName);
UserProfile chanandler =
context.Users.First(u => u.FullName == "Chanandler Bong");
Console.WriteLine("After reading: " + chanandler.FullName);
chanandler.FirstName = "Chandler";
chanandler.LastName = "Bing";
Console.WriteLine("After changing: " + chanandler.FullName);
}
We get this output:
It took a bit of work, but finally Chandler’s TV Guide can be delivered to the right person.
The obvious downside to this implementation is that the FullName calculation is duplicated in the database and in the UserProfile class.
This sample was written using Visual Studio 2012 and Entity Framework 5. Download the source code here.