When I try to Cast the projected list in the BuildTypes method, I get a list of null values. I have also tried using the .Cast(), but I get an error that some of the properties cannot be cast. I can post the error if it is helpful. Here is my code:
public class AuditActionType: EntityValueType
{
}
private List<T> BuildTypes<T>(XDocument xDocument) where T: EntityValueType
{
var types =
(from ty in xDocument.Descendants("RECORD")
select new
{
Id = GenerateGuid(),
Name = ty.Element("Name").Value,
EntityStatus = _activeEntityStatus,
DateCreated = DateTime.Now,
DateModified = DateTime.Now
} as T).ToList();
return types;
}
So I would call it like this:
var auditActorTypes = BuildTypes<AuditActorType>(auditActorTypesXml)
I have a ton of types I need to pull from an XML file and didn’t want to duplicate code for each type.
You are trying to cast an anonymous object as type
T, which cannot be done. The anonymous type is it’s own unique type and in no way related to theTpassed in.Instead, you could supply the
new()constraint on typeTto mean it needs a default constructor, and then perform anew T()instead of creating a new anonymous type:This is assuming, of course, that
Id,Name,EntityStatus,DateCreated, andDateModifiedare all properties of the baseEntityValueType.