views:

782

answers:

1

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'
+2  A: 

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
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
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
THis is the exact error message which I got while using your suggestion.
alice7
...which is not related to my suggestion but to your context. Please think about the error message a little.
Johannes Rudolph
got it thnx.It has to do about entity framework that IM using
alice7