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

c# ef-code-first entity-framework entity-framework-6 sql-server

Question

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?

1
1
10/3/2018 9:47:38 AM

Accepted Answer

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}";
0
9/11/2018 3:55:06 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow