gpt4 book ai didi

c# - EF Code First,同一对象的两个导航属性

转载 作者:行者123 更新时间:2023-11-30 16:04:49 28 4
gpt4 key购买 nike

我正在使用 EF Code First 查询和创建数据库。我的一个实体(关系)对同一个实体(事件)有两个导航属性。我的问题是,如果我使用 EF 创建数据库模式,它将创建四个外键列和约束,而不是两个。

相关代码部分如下:

事件类:

public class Activity {
public virtual ICollection<Relationship> Successors { get; set; }
public virtual ICollection<Relationship> Predecessors { get; set; }
}

关系类:

public class Relationship {
public virtual Activity Activity1 { get; set; }
public int Activity1_ID { get; set; }
public virtual Activity Activity2 { get; set; }
public int Activity2_ID { get; set; }
}

关系映射类:

this.HasRequired(t => t.Activity1)
.WithMany(t => t.Predecessors)
.HasForeignKey(m => m.Activity1_ID)
.WillCascadeOnDelete(false);
this.HasRequired(t => t.Activity2)
.WithMany(t => t.Successors)
.HasForeignKey(m => m.Activity2_ID)
.WillCascadeOnDelete(false);

数据库结构: enter image description here

有没有办法阻止创建最后两列?

最佳答案

这应该只为您创建 2 个外键列。

public class Activity
{
public int Id { set; get; }
public virtual ICollection<Relationship> Successors { get; set; }
public virtual ICollection<Relationship> Predecessors { get; set; }
}
public class Relationship
{
public int Id { set; get; }
public virtual Activity Activity1 { get; set; }
public int Activity1_ID { get; set; }
public virtual Activity Activity2 { get; set; }
public int Activity2_ID { get; set; }
}

还有我在 OnModelCreating 上指定关系/FK 性质的 DbContext 类。

public class MyDb: DbContext
{
public MyDb():base("EfDbContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Relationship>()
.HasRequired(f => f.Activity1)
.WithMany(f => f.Predecessors)
.HasForeignKey(g => g.Activity1_ID)
.WillCascadeOnDelete(false);

modelBuilder.Entity<Relationship>().
HasRequired(f => f.Activity2)
.WithMany(f => f.Successors)
.HasForeignKey(g => g.Activity2_ID)
.WillCascadeOnDelete(false);
}
}

enter image description here

关于c# - EF Code First,同一对象的两个导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34486478/

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