'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 1:[1]

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}";

Solution 2:[2]

You shouldn't duplicate the logic in the database and in the class. What you're probably missing is the instruction to EF Core that the value is generated in the database. Use ValueGeneratedOnAddOrUpdate in your OnModelCreating:

modelBuilder.Entity<MyTable>()
    .Property(t => t.FullName)
    .ValueGeneratedOnAddOrUpdate();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sean