C# 将 List<t> 转换或强制转换为 EntityCollection<T>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2364676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:45:39  来源:igfitidea点击:

convert or cast a List<t> to EntityCollection<T>

c#entity-frameworkcollections

提问by alice7

How would you to convert or cast a List<T>to EntityCollection<T>?

您将如何将 a 转换或强制转换List<T>EntityCollection<T>

Sometimes this occurs when trying to create 'from scratch' a collection of child objects (e.g. from a web form)

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

 Cannot implicitly convert type 
'System.Collections.Generic.List' to 
'System.Data.Objects.DataClasses.EntityCollection'

采纳答案by Johannes Rudolph

I assume you are talking about List<T>and EntityCollection<T>which is used by the Entity Framework. Since the latter has a completely different purpose (it's responsible for change tracking) and does not inherit List<T>, there's no direct cast.

我假设你正在谈论List<T>EntityCollection<T>所使用实体框架。由于后者具有完全不同的目的(它负责更改跟踪)并且不继承List<T>,因此没有直接强制转换。

You can create a new EntityCollection<T>and add all the List members.

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

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

Unfortunately EntityCollection<T>neither supports an Assign operation as does EntitySet used by Linq2Sql nor an overloaded constructor so that's where you're left with what I stated above.

不幸的是,它EntityCollection<T>既不支持 Linq2Sql 使用的 EntitySet 操作,也不支持重载的构造函数,所以这就是我上面所说的。

回答by David Sherret

In one line:

在一行中:

list.ForEach(entityCollection.Add);


Extension method:

扩展方法:

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;
}

Use:

用:

EntityCollection<ClassName> entityCollection = list.ToEntityCollection();

回答by Tim Partridge

No LINQ required. Just call the constructor

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

List<Entity> myList = new List<Entity>();
EntityCollection myCollection = new EntityCollection(myList);