ToList方法不适用于TrackableCollection [英] ToList method not available for TrackableCollection

查看:337
本文介绍了ToList方法不适用于TrackableCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



为了删除一个具有所有依赖实体的实体,我正在将一般的DeleteDependentEntities写为从EntityManager中的Delete方法调用。 (我们不是或不想依赖于CASCADE DELETE来设置我们的数据库中的关系。)DeleteDependentEntities可以反复扫描受影响的实体集的所有子项。



为了保持通用,所以它可以用于整个项目中的所有实体,我使用动态类型。



方法是如下:

  private void DeleteDependentEntities(dynamic entitySet,dynamic context)
{
if(entitySet!= null)
{
foreach(entitySet.ToList()中的动态项)
{
// 1.扫描子对象并删除子项
ProcessChildren(item,上下文);

// 2.删除此对象
context.DeleteObject(item);
}
}
}

它编译OK,运行时我得到以下错误:



'SLS.AnimalIntakeMgmt.DataTypes.TrackableCollection'不包含'ToList'的定义



因此,类型推断工作正常。 ToList定义的问题是奇怪的,因为TrackableCollection是基于ObservableCollection的,它反过来是基于Collection。



ToList是必要的,因为foreach循环失败,因为集合在循环中被修改。



欢迎所有的建议!

解决方案

问题是动态不适用于扩展方法。运行时仅查找动态对象本身定义的方法。

您需要调用ToList作为静态方法:

  foreach(Enumerable.ToList(entitySet)中的动态项目)

但我真的认为你如果可能,应该使用泛型。


We are working with Trackable Entities on top of EF 4.0.

In order to delete an Entity with all its dependent entities I'm writing a generic DeleteDependentEntities to be called from the Delete method in the EntityManager. (We don't, or don't want to, rely on a CASCADE DELETE to be set on the relations in our database.) The DeleteDependentEntities scans recursevly all Children of the subjected entitySet.

In order to keep it generic, so that it can be used for all entities throughout the project I'm using dynamic types.

The method is as follows:

private void DeleteDependentEntities(dynamic entitySet, dynamic context)
{
  if (entitySet != null)
  {
    foreach (dynamic item in entitySet.ToList())
    {
      // 1. Scan object for children and delete children
      ProcessChildren(item, context);

      // 2. Delete this object
      context.DeleteObject(item);
    }
  }
}

It compiles OK, but at runtime I get the following error:

'SLS.AnimalIntakeMgmt.DataTypes.TrackableCollection' does not contain a definition for 'ToList'

Hence the type inference worked OK. Problem with the ToList definition is weird since TrackableCollection is based on ObservableCollection which in its turn is based on Collection.

The ToList is necessary because otherwise the foreach loop fails because the collection is modified within the loop.

All suggestions are welcome!

解决方案

The problem is that dynamics don't work with extension methods. The runtime only looks for methods defined on the dynamic object itself.
You need to call ToList as a static method:

foreach (dynamic item in Enumerable.ToList(entitySet))

But I really think you should use generics if possible at all.

这篇关于ToList方法不适用于TrackableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆