将List 转换或转换为EntityCollection

您如何将List转换或转换为EntityCollection

有时,当尝试从头开始创建子对象的集合(例如,从Web表单)时,会发生这种情况

 无法隐式转换类型 
 'System.Collections.Generic.List'到 
 'System.Data.Objects.DataClasses.EntityCollection' 

我假设您正在讨论entity framework使用的ListEntityCollection 。 由于后者具有完全不同的目的(它负责更改跟踪)并且不inheritanceList ,因此没有直接强制转换。

您可以创建一个新的EntityCollection并添加所有List成员。

 var entityCollection = new EntityCollection(); foreach (var item m in list) { entityCollection.Add(m); } 

不幸的是, EntityCollection既不像Linq2Sql使用的EntitySet那样支持Assign操作,也不支持重载的构造函数,所以这就是我在上面所说的内容。

在一行中:

 list.ForEach(entityCollection.Add); 

扩展方法:

 public static EntityCollection ToEntityCollection(this List list) where T : class { EntityCollection entityCollection = new EntityCollection(); list.ForEach(entityCollection.Add); return entityCollection; } 

使用:

 EntityCollection entityCollection = list.ToEntityCollection(); 

不需要LINQ。 只需调用构造函数即可

 List myList = new List(); EntityCollection myCollection = new EntityCollection(myList);