convert or cast an EntityCollectionT> from a Listt>

c# collections entity-framework

Question

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

When attempting to build a collection of child objects "from scratch," this might sometimes happen (e.g. from a web form)

 Cannot implicitly convert type 
'System.Collections.Generic.List' to 
'System.Data.Objects.DataClasses.EntityCollection'
1
23
6/9/2010 11:43:58 PM

Accepted Answer

I believe you're referring toList<T> and EntityCollection<T> which the Entity Framework use. Since the latter serves an entirely different function (it is in charge of recording changes) and does not inheritList<T> there is no clear cast.

You may start a new one.EntityCollection<T> and include each member of the List.

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

Unfortunately EntityCollection<T> You are left with what I just said since neither provides an overloaded constructor nor an Assign action, as the EntitySet utilized by Linq2Sql does.

28
3/2/2010 4:24:15 PM

Popular Answer

One sentence:

list.ForEach(entityCollection.Add);

Extension strategy:

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();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow