【发布时间】:2010-01-05 16:32:51
【问题描述】:
为了促进控件重用,我们创建了一个包含三个独立项目的解决方案:控件库、Silverlight 客户端和 ASP.NET 后端。控件库没有引用 RIA 服务生成的数据模型类,因此当它需要与之交互时,我们使用反射。
到目前为止,这一切都很好,但我遇到了一个问题。我有一个 DataGrid 控件,用户可以在其中选择一行,按下“删除”按钮,它应该从集合中删除实体。在 DataGrid 类中,我有以下方法:
private void RemoveEntity(Entity entity)
{
// Use reflection to remove the item from the collection
Type sourceType = typeof(System.Windows.Ria.EntityCollection<>);
Type genericType = sourceType.MakeGenericType(entity.GetType());
System.Reflection.MethodInfo removeMethod = genericType.GetMethod("Remove");
removeMethod.Invoke(this._dataGrid.ItemsSource, new object[] { entity });
// Equivalent to: ('Foo' derives from Entity)
// EntityCollection<Foo> ec;
// ec.Remove(entity);
}
这适用于客户端,但在域服务上,在 Submit() 方法期间会生成以下错误:
"UPDATE 语句与 FOREIGN KEY 约束 “********”。冲突发生在 数据库“********”,表“********”, 柱子 '********'。该声明有 被终止了。”
我注意到的一件事是调用了 UpdateFoo() 服务方法,而不是域服务上的 DeleteFoo() 方法。进一步检查显示实体将进入 ModifiedEntities ChangeSet 而不是 RemovedEntities ChangeSet。我不知道这是否是问题,但它似乎不对。
任何帮助将不胜感激,谢谢,
更新
我确定问题肯定来自对 EntityCollection.Remove() 方法的反射调用。由于某种原因,调用它会导致实体的 EntityState 属性更改为 EntityState.Modified 而不是 EntityState.Deleted。
即使我尝试通过完全绕过 DataGrid 从集合中删除,我也会遇到完全相同的问题:
Entity selectedEntity = this.DataContext.GetType().GetProperty("SelectedEntity").GetValue(this.DataContext, null) as Entity;
object foo = selectedEntity.GetType().GetProperty("Foo").GetValue(selectedEntity, null);
foo.GetType().InvokeMember("Remove", BindingFlags.InvokeMethod, null, foo, new object[] { entity });
作为测试,我尝试修改 UpdateFoo() 域服务方法来实现删除,它成功地删除了实体。这表明 RIA 服务调用工作正常,只是调用了错误的方法(更新而不是删除。)
public void UpdateFoo(Foo currentFoo)
{
// Original update implementation
//if ((currentFoo.EntityState == EntityState.Detached))
// this.ObjectContext.AttachAsModified(currentFoo, this.ChangeSet.GetOriginal(currentFoo));
// Delete implementation substituted in
Foo foo = this.ChangeSet.GetOriginal(currentFoo);
if ((foo.EntityState == EntityState.Detached))
this.ObjectContext.Attach(foo);
this.ObjectContext.DeleteObject(foo);
}
【问题讨论】:
标签: entity-framework reflection silverlight-3.0 wcf-ria-services