简体   繁体   中英

EF Core: Ignore property only on save

I have mapped an entity mapped to a database view (for querying data) and also to a table (for inserting, updating data).

To map an entity to the database view, I use this code ( from the EF 5.0 docs ):

modelBuilder
    .Entity<Blog>()
    .ToTable("Blogs")
    .ToView("BlogsView");

In the database view, I have additional columns computed by the database (they are not present in a table). I need these additional columns on every select query, but I need to ignore them on save and update.

The [NotMapped] data annotation is not a solution because it ignores properties at all commands (select, update, etc.). When I omit the [NotMapped] data annotation, however, EF throws error on insert because EF tries to insert values to columns which do not exist in the table.

The [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attribute is also not a solution because, in the SQL insert statement, EF produces a query which selects the columns from table, not from database view.

Is there any solution to achieve this with the Fluent API without separately mapping different entities to the view (with the additional columns) and the table (without the additional columns)?

You have to set both BeforeSaveBehavior (for insert) and AfterSaveBehavior (for update) of the entity property to Ignore .

Currently there is no fluent API for that, but you could use the metadata API, eg

modelBuilder.Entity<Blog>().Property(e => e.ViewProp1)
    .Metadata.SetBeforeSaveBehavior(PropertySaveBehavior.Ignore);
modelBuilder.Entity<Blog>().Property(e => e.ViewProp1)
    .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM