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

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

Question

Say I have an entity like in an Entity Framework project.

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

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

What's theFullName on a SQL Server 2012 database is calculated as the concatenation ofFirstName and LastName .

This whole table is fully loaded locally at the beginning of the project. the use ofDbContext.DbSet<MyTable>.Load()

I am in run-time

  1. Making a code example of this
  2. setting this object's First and Last Name attributes.
  3. Including this example in theDbSet of theDbContext
  4. Calling DbContext.SaveChanges()

Following the call toSaveChanges() I anticipated theFullName computed attribute of the object that will contain the calculated value. But alas, it doesn't seem like this is going on?

How can I insert the database's calculated value 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.

You didn't join them together into theFullName Since you are utilising EF-Code First, you need provide it in your getter, like in the following example:

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

Or, using a more recent 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