Search code examples
c#sql-serverentity-frameworkentity-framework-6ef-code-first

Getting the result of a computed column from database into an entity


In a project using Entity Framework, say I have an entity such as

[Table("MyTable")]
public partial class MyTable
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [DatabaseGenerated( DatabaseGeneratedOption.Computed)]
    public string FullName { get; set; }
}

Where the FullName is computed on a SQL Server 2012 database as a concatenation of FirstName and LastName.

At the start of the project this entire table is completely loaded locally. That is, via DbContext.DbSet<MyTable>.Load()

At run-time I am

  1. Creating an instance of this in code
  2. Setting the First and Last Name properties of this object.
  3. Adding this instance to the DbSet of the DbContext
  4. Calling DbContext.SaveChanges()

Now, after the call to SaveChanges() I was expecting the FullName computed property of the entity to be populated with the computed value. But sadly, this doesn't appear to be happening?

How can I get the computed value from the database into my entity object?


Solution

  • Where the FullName is computed on a SQL Server 2012 database as a concatenation of FirstName and LastName.

    Well, you didn't concatenate them into the FullName property in your class, since you are using EF-Code First, so you should specify it in your getter, something like this:

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

    Or with newer version of C#, you can:

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public string FullName => $"{FirstName} {LastName}";