ali*_*ce7 23 c# collections entity-framework
你会如何转换或投射List<T>到EntityCollection<T>?
有时,当尝试从头开始创建子对象的集合(例如,从Web表单)时,会发生这种情况
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Data.Objects.DataClasses.EntityCollection'
Joh*_*lph 28
我假设你正在谈论List<T>和EntityCollection<T>所使用实体框架.由于后者具有完全不同的目的(它负责变更跟踪)并且不继承List<T>,因此没有直接演员.
您可以创建一个新的EntityCollection<T>并添加所有List成员.
var entityCollection = new EntityCollection<TEntity>();
foreach (var item m in list)
{
entityCollection.Add(m);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,EntityCollection<T>它既不像Linq2Sql使用的EntitySet那样支持Assign操作,也不支持重载的构造函数,所以这就是我在上面所说的内容.
Dav*_*ret 15
在一行中:
list.ForEach(entityCollection.Add);
Run Code Online (Sandbox Code Playgroud)
扩展方法:
public static EntityCollection<T> ToEntityCollection<T>(this List<T> list) where T : class
{
EntityCollection<T> entityCollection = new EntityCollection<T>();
list.ForEach(entityCollection.Add);
return entityCollection;
}
Run Code Online (Sandbox Code Playgroud)
使用:
EntityCollection<ClassName> entityCollection = list.ToEntityCollection();
Run Code Online (Sandbox Code Playgroud)