ToList method not available for TrackableCollection

徘徊边缘 提交于 2019-12-10 18:44:33

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/6663593/tolist-method-not-available-for-trackablecollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!