Let’s consider the following classes:
public class BaseEntity
{
public BaseEntity()
{
Created = DateTime.Now;
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual Guid Id { get; set; }
public virtual DateTime Created { get; set; }
[Required]
public virtual string Code { get; set; }
}
public interface IBaseHistory
{
string EntityName { get; set; }
string LoggedUserData { get; set; }
string ModificationType { get; set; }
string ExtraInfo { get; set; }
}
public abstract class OrderBase : BaseEntity
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
public class Order : OrderBase
{
public Order()
{
}
public virtual Client Owner { get; set; }
}
public class OrderHistory : OrderBase, IBaseHistory
{
public string EntityName { get; set; }
public string LoggedUserData { get; set; }
public string ModificationType { get; set; }
public string ExtraInfo { get; set; }
}
I’m using code first approach in my project. I want to create history entity for each entity in my model. To do this I had to use approach from: https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt To each history table I also want to add some extra field such as: ModificationType or EntityName etc. To implement this idea I used IBaseHistory interface as you see in my example. The question is: How to copy base class properties of one entity object (Prop1 and Prop2 of Order entity) to the second entity object(OrderHistory) which inherits from the same base class as first entity object (OrderBase) ? The easiest way I see to do this is to use constructor such as:
public class OrderHistory : OrderBase, IBaseHistory
{
public string EntityName { get; set; }
public string LoggedUserData { get; set; }
public string ModificationType { get; set; }
public string ExtraInfo { get; set; }
public OrderHistory()
{
}
public OrderHistory(OrderBase orderBase)
{
this.Prop1 = orderBase.Prop1;
this.Prop2 = orderBase.Prop2;
}
}
And then I can easily do:
Order order= new Order() {Prop1 = "val1", Prop2 = "val2"};
OrderHistory orderHistory = new OrderHistory(order);
What if my entity has 40 fields? In such case I have to add 40 lines of code and what if I forget about one field? I thought about using AutoMapper but I also don’t know if it’s a good way to solve the problem. I want to solve the problem using the simplest way. Im open for any suggestions. Cheers.