I'm having a bit of trouble writing a class that uses generics because this is the first time that I have had to create a class that uses generics.
All I am trying to do is create a method that converts a List to an EntityCollection.
I am getting the compiler error: The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Objects.DataClasses.EntityCollection'
Here is the code that I am trying to use:
public static EntityCollection<T> Convert(List<T> listToConvert)
{
EntityCollection<T> collection = new EntityCollection<T>();
// Want to loop through list and add items to entity
// collection here.
return collection;
}
It is complaining about the the EntityCollection collection = new EntityCollection() line of code.
If anyone could help me out with this error, or explain to me why I am receiving it I would greatly appreciate it. Thanks.
Read up on generic constraints in .NET. Specifically, you need a "where T : class" constraint, since EntityCollection cannot store value types (C# structs), but unconstrained T can include value types. You will also need to add a constraint to say that T must implement IEntityWithRelationships, again because EntityCollection demands it. This results in something such as:
public static EntityCollection<T> Convert<T>(List<T> listToConvert) where T : class, IEntityWithRelationships
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With