23

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

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

 Cannot implicitly convert type 
'System.Collections.Generic.List' to 
'System.Data.Objects.DataClasses.EntityCollection'
p.campbell
  • 98,673
  • 67
  • 256
  • 322
alice7
  • 3,834
  • 14
  • 64
  • 93

3 Answers3

30

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.

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

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.

Johannes Rudolph
  • 35,298
  • 14
  • 114
  • 172
  • The object could not be added to the EntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object. I got this error – alice7 Mar 02 '10 at 16:44
  • This has nothing to do with the question itself but is rather related to your specific scenario. Don't you think it's a very descriptive error message? – Johannes Rudolph Mar 02 '10 at 17:02
  • THis is the exact error message which I got while using your suggestion. – alice7 Mar 02 '10 at 17:06
  • 4
    ...which is not related to my suggestion but to your context. Please think about the error message a little. – Johannes Rudolph Mar 02 '10 at 17:09
  • got it thnx.It has to do about entity framework that IM using – alice7 Mar 02 '10 at 17:27
  • Old but just to complete the answer for others who may find this (like me): You need to detach your item from the context before adding it to another entitycollection. context.Detach(item) – BritishDeveloper Apr 12 '12 at 16:18
15

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();
David Sherret
  • 101,669
  • 28
  • 188
  • 178
-1

No LINQ required. Just call the constructor

List<Entity> myList = new List<Entity>();
EntityCollection myCollection = new EntityCollection(myList);
Tim Partridge
  • 3,365
  • 1
  • 42
  • 52