【问题标题】:How can I through the OnModelCreating method create foreign keys dynamically如何通过 OnModelCreating 方法动态创建外键
【发布时间】:2017-02-03 03:36:48
【问题描述】:

在我的 EF6 模型上,我创建了某些包含我希望跨多个实体继承的属性/列的基类。

这是一个简单的概念示例:

public class Replaceable 
{
    [Column("REPLACING")]
    public int Replacing { get; set; }
}

[Table("PARTS")]
public class Part : Replaceable
{
    [Column("ID"), Key]
    public int Id { get; set; }

    [Column("PART_NUMBER")]
    public string PartNumber { get; set; }
}

所以 REPLACING 属性 & 列将被继承到 Part-class/PARTS-table。

REPLACING 列应该指向同一个表中的一个 ID。例如,如果您更换了一个零件,您想跟踪什么替换了什么。

我想通过OnModelCreating 做的(如果可能的话)是:

  • 获取所有继承自 Replaceable 的实体。
  • 将 REPLACING 列标记为外键并将其指向实体的主键(PART_ID、COMPONENT_ID 等)。

这里的诀窍是如何获取每个实体表的 ID 列的名称,因为它们都不是 ID,而是 PART_ID、COMPONENT_ID 等。

这甚至可能吗?也欢迎另一种做法。

【问题讨论】:

  • 也许自己创建一个属性并添加到你要使用的属性中,然后用反射把它拉出来?
  • @DavidG:好的,这是一个选项。我为设置小数精度做了类似的事情。您能否设置一个示例,在获取属性后您取出每个类的主键?

标签: c# entity-framework


【解决方案1】:

您可以使用基本配置类:

public abstract class ReplaceableConfiguration<T> : EntityTypeConfiguration<T>
    where T : Replaceable
{
    public ReplaceableConfiguration()
    {
        this.Property(r => r.Replacing).HasColumnName(typeof(T).Name + "_ID");
    }
}

并根据需要派生尽可能多的具体类。

public class PartConfiguration : ReplaceableConfiguration<Part>
{ }

public class ComponentConfiguration : ReplaceableConfiguration<Component>
{ }

我只尝试了两个类:

modelBuilder.Configurations.Add(new PartConfiguration());
modelBuilder.Configurations.Add(new ComponentConfiguration());

这给了我这个 DDL:

CREATE TABLE [dbo].[PARTS] (
    [ID] [int] NOT NULL IDENTITY,
    [PART_NUMBER] [nvarchar](max),
    [Part_ID] [int] NOT NULL,
    CONSTRAINT [PK_dbo.PARTS] PRIMARY KEY ([ID])
)

CREATE TABLE [dbo].[COMPONENTS] (
    [ID] [int] NOT NULL IDENTITY,
    [COMPONENT_NUMBER] [nvarchar](max),
    [Component_ID] [int] NOT NULL,
    CONSTRAINT [PK_dbo.COMPONENTS] PRIMARY KEY ([ID])
)

【讨论】:

    猜你喜欢
    • 2023-02-08
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多