2

我得到了例外: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),我该如何解决?

4

1 回答 1

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();
于 2013-07-25T15:27:33.060 回答