简体   繁体   中英

how to insert/update entity framework entities that are partially mapped to a view?

I have a database with an 'Equipment' table and a view called 'EquipmentStatuses' that does something complicated to associate each entry in the 'Equipment' table to some aggregated value from another table and returns a simple 2 column view with the EquipmentId and a calculated value.

I have mapped the 'Equipment' table to an Equipment entity and created one extra scalar field that maps to the calculated field from the View. It all works fine when I just retrieve records from the database, but when I try to insert or update the Equipment table I get an error from Entity Framework:

Unable to update the EntitySet 'EquipmentStatuses' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.

It seems that entity framework is trying to insert something into the view, but fails because I haven't actually told EF how to do that. However, the single field from the view doesn't need to be updated because it's calculated automatically from another table.

Is there a way to tell entity framework to ignore the view and just update the Equipment table without writing all sorts of boilerplate insert/update/delete stored procedures?

I'm using EF6 with a SQL Server database.

You can detach that object from the context:

dbContext.Entry(EquipmentStatuses).State = EntityState.Detached;

If this is MVC you could also compose viewmodels, send them to the view and then map them back to the proper entities on the POST. A tool like Automapper is great for this.

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