假设我有两个不同的课程。它们共享一些属性,但也有一些单独的属性。
public class A
{
// Shared properties
public int Id { get; set; }
public DateTime CreatedDtm { get; set; }
public string CreatedBy { get; set; }
// Individual properties
public string PhoneNumber { get; set; }
public string EmailAddress { get; set; }
}
public class B
{
// Shared properties
public int Id { get; set; }
public DateTime CreatedDtm { get; set; }
public string CreatedBy { get; set; }
// Individual properties
public string StreetAddress { get; set; }
public string PostalCode{ get; set; }
public string City{ get; set; }
}
现在的技巧是,我想将这两种类型存储为同一实体。如果我将各个属性转换为 JSON,这是可能的。所以我可以创建一个共享实体,如下所示:
public class C
{
// Shared properties
public int Id { get; set; }
public DateTime CreatedDtm { get; set; }
public string CreatedBy { get; set; }
// Individual properties
public object IndividualProperties { get; set; }
}
但如果我这样做,我就会失去静态类型语言的所有优势以及多态性的所有优势,这样做(例如class A
可能有一些不同的验证class B
).
在保存实体之前,是否有某种方法可以通过实体框架(核心)进行转换?我当然可以自己编写映射,但我感觉应该有一个捷径......
基本上,我想做这样的事情(不管它是接口、抽象类还是完全不同的东西):
public void AddEntity(ISomeSharedInterface entity)
{
C sharedEntity = SomeMappingMethod(entity);
db = new Context();
db.SharedEntities.Add(sharedEntity);
db.SaveChanges();
}
如果您对这个设计感到好奇,它是用于自动化过程的。在此过程中需要填写的各种子表单有所不同,但我希望将所有项目存储在同一个表中。