简体   繁体   English

如何插入/更新部分映射到视图的实体框架实体?

[英]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. 我有一个带有“设备”表和一个名为“ EquipmentStatuses”的视图的数据库,该数据库将将“ Equipment”表中的每个条目与另一个表中的某个聚合值相关联,执行一些复杂的操作,并返回一个带有EquipmentId和一个简单的2列视图计算值。

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: 当我只是从数据库中检索记录时,一切都很好,但是当我尝试插入或更新Equipment表时,我从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. 似乎实体框架试图在视图中插入一些东西,但是失败了,因为我实际上没有告诉EF如何做到这一点。 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. 我将EF6与SQL Server数据库一起使用。

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. 如果这是MVC,则还可以组成视图模型,将其发送到视图,然后将其映射回POST上的适当实体。 A tool like Automapper is great for this. 像Automapper这样的工具非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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