Entity Framework Code First - how to ignore a column when saving

I have a Client class mapped to a database table using Entity Framework code. The table has a computed field that I need in my Client class, but I understand that I cannot write to this field. Is there a way to configure the Entity Framework to ignore the property when saving, but to include the property when reading?

I tried using the Ignore method in my configuration class or using the [NotMapped] attribute, but this prevents the property from being read from the database.

+5
source share
2 answers

You can use DatabaseGeneratedAttributewith the option DatabaseGeneratedOption.Computed:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public ComputedPropertyType ComputedProperty { get; set; }

api, HasDatabaseGeneratedOption DbContext:

public class EntitiesContext : DbContext
{
    public DbSet<EntityType> Enities { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<EntityType>().Property(e => e.ComputedProperty).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
    }
}
+9

:

modelBuilder
    .Entity<MyEntityType>()
    .Property(_ => _.MyProperty)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
+3

All Articles