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

让人想犯罪 __ 提交于 2019-12-07 06:36:41

问题


I have a class called Client mapped to a database table using Entity Framework code first. The table has a computed field that I need available in my Client class, but I understand that it won't be possible to write to this field. Is there a way of configuring Entity Framework to ignore the property when saving, but include the property when reading?

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


回答1:


You can use DatabaseGeneratedAttribute with DatabaseGeneratedOption.Computed option:

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

or if you prefer fluent api you can use HasDatabaseGeneratedOption method in your DbContext class:

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



回答2:


Mark property as computed:

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


来源:https://stackoverflow.com/questions/15829523/entity-framework-code-first-how-to-ignore-a-column-when-saving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!