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'

3 Answers 3

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.

6
  • 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 2, 2010 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? Mar 2, 2010 at 17:02
  • THis is the exact error message which I got while using your suggestion.
    – alice7
    Mar 2, 2010 at 17:06
  • 4
    ...which is not related to my suggestion but to your context. Please think about the error message a little. Mar 2, 2010 at 17:09
  • got it thnx.It has to do about entity framework that IM using
    – alice7
    Mar 2, 2010 at 17:27
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();
1
  • 5
    In one even shorter line, list.ForEach(entityCollection.Add);
    – AakashM
    Oct 25, 2012 at 9:38
-1

No LINQ required. Just call the constructor

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.