[英]How can I through the OnModelCreating method create foreign keys dynamically
On my EF6 model I have created certain base classes that contain properties/columns that I want to be inherited across several entities.在我的 EF6 模型上,我创建了某些基类,其中包含我希望跨多个实体继承的属性/列。
Here is a simple example of the concept:这是这个概念的一个简单示例:
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; }
}
So the REPLACING property & column will be inherited to Part-class/PARTS-table.所以 REPLACING 属性 & 列将被继承到 Part-class/PARTS-table。
The REPLACING column is supposed to point towards an ID in the same table. REPLACING 列应该指向同一个表中的 ID。 For example if you replace a part you want to keep track of what replaced what.
例如,如果您更换零件,您希望跟踪更换的零件。
What I want to do (if possible) through OnModelCreating
is:我想做(如果可能)通过
OnModelCreating
是:
The trick here is how to get the name of the ID column of each entity's table since all of them are not called ID but PART_ID, COMPONENT_ID etc.这里的技巧是如何获取每个实体表的 ID 列的名称,因为所有这些都不称为 ID,而是称为 PART_ID、COMPONENT_ID 等。
Is this even possible?这甚至可能吗? An alternative practice is also welcome.
另一种做法也是受欢迎的。
You can use a base configuration class:您可以使用基本配置类:
public abstract class ReplaceableConfiguration<T> : EntityTypeConfiguration<T>
where T : Replaceable
{
public ReplaceableConfiguration()
{
this.Property(r => r.Replacing).HasColumnName(typeof(T).Name + "_ID");
}
}
And derive as many concrete classes as you want.并根据需要派生尽可能多的具体类。
public class PartConfiguration : ReplaceableConfiguration<Part>
{ }
public class ComponentConfiguration : ReplaceableConfiguration<Component>
{ }
I tried this with just two classes:我只用两个类尝试过这个:
modelBuilder.Configurations.Add(new PartConfiguration());
modelBuilder.Configurations.Add(new ComponentConfiguration());
Which gave me this DDL:这给了我这个 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])
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.