gpt4 book ai didi

c# - 多个实体到同一个 DbSet

转载 作者:行者123 更新时间:2023-12-04 10:47:39 26 4
gpt4 key购买 nike

假设我有两个不同的类(class)。它们共享一些属性,但也有一些单独的属性。

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 有一些不同的验证)。

在通过 Entity Framework (核心)保存实体之前,是否有某种方法可以进行转换?我当然可以自己编写映射,但我觉得应该有一个捷径......

基本上,我想做这样的事情(不管它是接口(interface)、抽象类还是完全不同的东西):
public void AddEntity(ISomeSharedInterface entity) 
{
C sharedEntity = SomeMappingMethod(entity);
db = new Context();
db.SharedEntities.Add(sharedEntity);
db.SaveChanges();
}

如果您想知道这种设计,它是针对自动化过程的。在此过程中需要填写的各种子表格各不相同,但我想将所有项目存储在同一个表中。

最佳答案

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

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 .

关于c# - 多个实体到同一个 DbSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59628432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com