【发布时间】:2020-04-24 23:03:31
【问题描述】:
假设我有两个不同的课程。它们共享一些属性,但也有一些单独的属性。
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();
}
如果您想知道这种设计,它是针对自动化流程的。在这个过程中需要填写的各种子表格各不相同,但我想将所有项目存储在同一个表中。
【问题讨论】:
标签: c# entity-framework entity-framework-core mapping