我有以下课程:
public class Condition
{
public int Id {get;set; }
public Condition ParentCondition {get;set;}
public Action ParentAction {get;set;}
public string Whatever {get;set;}
}
public class Action
{
public int Id {get;set; }
public Condition ParentCondition {get;set;}
public Action ParentAction {get;set;}
public string Whatever {get;set;}
}
所以两者,条件和动作可能有一个条件或一个动作作为父母(如果两个都为空则没有)
我试着把它放到一个SQL数据库上但是以某种方式丢失了。所以我想要实现的东西就像(伪代码)
表Condition
:
int ConditionParent
int ActionParent
表Action
:
int ConditionParent
int ActoinParent
我尝试使用流畅的api:
modelBuilder.Entity<Condition>()
.ToTable("Condition")
.HasOptional(c => c.ParentAction)
.WithRequired(a => a.ParentCondition);
但是当我这样做时,Action
表看起来很好,但条件的迁移代码根本没有动作父代的列。
有什么需要改变?
答案 0 :(得分:1)
我通过明确添加ID来解决这个问题:
public class Condition
{
public int Id {get;set; }
public int? ParentConditionId {get;set;}
public virtual Condition ParentCondition {get;set;}
public int? ParentActionId {get;set; }
public virtual Action ParentAction {get;set;}
public string Whatever {get;set;}
}
public class Action
{
public int Id {get;set; }
public int ParentConditionId {get;set;}
public virtual Condition ParentCondition {get;set;}
public int? ParentActionId {get;set;}
public virtual Action ParentAction {get;set;}
public string Whatever {get;set;}
}
答案 1 :(得分:0)
Conditions
表确实有一个父行为列!它是主键,同时是Action
的外键。
查看表的(基本)创建代码:
CREATE TABLE [dbo].[Actions](
[Id] [int] NOT NULL,
[ParentAction_Id] [int] NULL,
CONSTRAINT [PK_dbo.Actions] PRIMARY KEY CLUSTERED ([Id]))
ALTER TABLE [dbo].[Actions] ADD CONSTRAINT [FK_dbo.Actions_dbo.Actions_ParentAction_Id]
FOREIGN KEY([ParentAction_Id]) REFERENCES [dbo].[Actions] ([Id])
-- Here: primary key Id is foreign key to Condition
ALTER TABLE [dbo].[Actions] ADD CONSTRAINT [FK_dbo.Actions_dbo.Conditions_Id]
FOREIGN KEY([Id]) REFERENCES [dbo].[Conditions] ([Id])
CREATE TABLE [dbo].[Conditions](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ParentCondition_Id] [int] NULL,
CONSTRAINT [PK_dbo.Conditions] PRIMARY KEY CLUSTERED ([Id])
)
ALTER TABLE [dbo].[Conditions] ADD CONSTRAINT [FK_dbo.Conditions_dbo.Conditions_ParentCondition_Id]
FOREIGN KEY([ParentCondition_Id]) REFERENCES [dbo].[Conditions] ([Id])
这是因为Action
- Condition
是1:1的关联。 EF始终通过此PK / FK构造实现所需的1:1关联。这是有道理的:如果没有必需的Action
父级,Condition
就不可能存在。保证Action
“借用”Condition
PK值的最佳方法。