I am trying to create an extension method that builds a POCO object (copies all the fields) for an Entity Object.
When Entity object is simple (no navigation, no sub collections), it works fine. I want to improve it so it could also deal with sub-entities.
For this example I take Nortwind database and use Customer and Order entities. My POCOs:
public class CustomerPOCO : BaseDataItemModel
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
List<OrderPOCO> orders;
[PropertySubCollection]
public List<OrderPOCO> Orders
{
get { return orders; }
set { orders = value; }
}
public CustomerPOCO()
{
orders = new List<OrderPOCO>();
}
}
public class OrderPOCO : BaseDataItemModel
{
public int OrderID { get; set; }
public string ShipName { get; set; }
public string ShipCity { get; set; }
}
Extension Method:
public static void CopyPropertiesFrom<TObjectTarget>(
this ICollection<TObjectTarget> targetitems, System.Collections.IEnumerable sourceitems)
where TObjectTarget : new()
{
foreach (var source in sourceitems)
{
TObjectTarget targetObject = new TObjectTarget();
PropertyInfo[] allProporties = source.GetType().GetProperties();
PropertyInfo targetProperty;
foreach (PropertyInfo fromProp in allProporties)
{
targetProperty = targetObject.GetType().GetProperty(fromProp.Name);
if (targetProperty == null) continue;
if (!targetProperty.CanWrite) continue;
//check if property in target class marked with SkipProperty Attribute
if (targetProperty.GetCustomAttributes(typeof(SkipPropertyAttribute), true).Length != 0) continue;
//Sub Collection -> set it here
if (targetProperty.GetCustomAttributes(typeof(PropertySubCollection), true).Length != 0)
{
}
else
targetProperty.SetValue(targetObject, fromProp.GetValue(source, null), null);
}
targetitems.Add(targetObject);
}
}
static void Main(string[] args)
{
List<CustomerPOCO> customers;
using (NorthwindEntities northcontext = new NorthwindEntities())
{
var cus = from customer in northcontext.Customers
select customer;
customers = new List<CustomerPOCO>();
customers.CopyPropertiesFrom(cus);
}
}
Note: Extension should know the type of sub-entity and a type of sub-poco...