【问题标题】:Multiple entities to same DbSet多个实体到同一个 DbSet
【发布时间】: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


    【解决方案1】:

    如果您创建一个抽象基类,这应该可以在没有任何额外配置的情况下工作:

    public abstract class Base
    {
        // Shared properties
        public int Id { get; set; }
        public DateTime CreatedDtm { get; set; }
        public string CreatedBy { get; set; }
    }
    
    public class A : Base
    {
        // Individual properties
        public string PhoneNumber { get; set; }
        public string EmailAddress { get; set; }
    }
    
    public class B : Base
    {
        // Individual properties
        public string StreetAddress { get; set; }
        public string PostalCode{ get; set; }
        public string City{ get; set; }
    }
    
    class Context : DbContext
    {
        DbSet<Base> Bases { get; set; }
    }
    
    public void AddEntity(Base entity) 
    {
        using (db = new Context())
        {
            db.Bases.Add(entity);
            db.SaveChanges();
        }
    }
    

    更多信息here

    【讨论】:

    • 所以这意味着我不会在我的数据库中获得 JSON blob,而是每个属性的列,然后 null 如果该属性没有值,则对于该特定类,对?
    • @Noceo 是正确的。它还将添加一个“影子”鉴别器列来识别每一行的实体类型。
    • 这是一个有趣的方法。尽管我更喜欢使用 JSON blob 的最终结果,但我确实喜欢与 EF Core 一起使用的部分,而不是反对它(就像我正在做的那样)。我会告诉你,结果如何。
    猜你喜欢
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 2018-11-06
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多