Updated on Kisan Patel
This tutorial will show you how to specify computed column in entity framework code first using DatabaseGenerated attribute?
If you’re mapping your Code First classes to tables that contain computed columns, you don’t want Entity Framework to try to update those columns. But you do want EF to return those values from the database after you’ve inserted or updated data. You can use the DatabaseGenerated
annotation to flag those properties in your class along with the Computed enum. Other enums are None and Identity.
public class Student { public int Id { get; set; } public string Name { get; set; } public int? Mark1 { get; set; } public int? Mark2 { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public string Total { get; private set; } }
Here, we have specify DatabaseGenerated
attribute to our Total
property. This is a hint to let Entity Framework Code First know that the database will be computing this property for us.
OR with fluent mapping:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity().Property(t => t.Total) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed); base.OnModelCreating(modelBuilder); }