原始状态实例的类型错误

时间:2013-07-25 15:19:50

标签: c# linq-to-sql

当使用以下缩减代码的版本时,我得到例外: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 DerivedFromTableclass DerivedFromTable : Table

此异常的含义是什么(显然((Table)derivedFromTable) is Tableexisting is Table)以及如何解决?

1 个答案:

答案 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();