You cannot do this with the current code, since new { }
creates an anonymous type that is not related to T (it is neither a child, nor has type T). Instead, you can implement Id
, Name
, EntityStatus
, DateCreated
and DateModified
as properties in the EntityValueType
class and change:
private List<T> BuildTypes<T>(XDocument xDocument) where T: EntityValueType
To:
private List<T> BuildTypes<T>(XDocument xDocument) where T: EntityValueType, new()
Indicates that any type argument passed to our method should have a constructor without parameters, which allows you to use an object of type T to actually build it, mainly by changing:
select new { ... } as T
To:
select new T { ... }
Final result:
public class EntityValueType { public Guid Id { get; set; } public string Name { get; set; } // Change this to the correct type, I was unable to determine the type from your code. public string EntityStatus { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } } public class AuditActionType: EntityValueType { } private List<T> BuildTypes<T>(XDocument xDocument) where T: EntityValueType, new() { return (from ty in xDocument.Descendants("RECORD") select new T { Id = GenerateGuid(), Name = ty.Element("Name").Value, EntityStatus = _activeEntityStatus, DateCreated = DateTime.Now, DateModified = DateTime.Now }).ToList(); }
source share