当使用以下缩减代码的版本时,我得到例外:InvalidOperationException: The original state instance has the wrong type.
:
Table existing = context.Tables.Single(t => t.Key == derivedFromTable.Key);
context.Tables.Attach((Table)derivedFromTable, existing); //thrown here
context.SubmitChanges();
derivedFromTable is DerivedFromTable
和class DerivedFromTable : Table
。
此异常的含义是什么(显然((Table)derivedFromTable) is Table
和existing is Table
)以及如何解决?
答案 0 :(得分:1)
(Table)derivedFromTable
强制转换是没有意义的,因为Attach()
方法已经接受类型为Table
的参数,因此扩展的强制转换是隐含的。
然而,这并不重要,因为Linq to SQL动态检查传入对象的类型,并且基本上它不支持将派生类型视为基本实体(也因为转换不会更改实例的实际类型,它只是更改其静态接口)。因此,如果要执行此操作,则需要首先使用类似AutoMapper的方法将派生实例的属性复制到基类型的实例。例如:
Table existing = context.Tables.Single(t => t.Key == derivedFromTable.Key);
Table table = Mapper.Map<DerivedFromTable, Table>(derivedFromTable);
context.Tables.Attach(table , existing);
context.SubmitChanges();