嗨,我的问题是,当我运行 Add-Migration 时,我的数据库模型最终会像这样。FK 四次而不是两次。
CreateTable(
"dbo.IntressentIntressent",
c => new
{
ParentIntressentId = c.Int(nullable: false),
ChildIntressentId = c.Int(nullable: false),
Aktieantal = c.Int(nullable: false),
Agare = c.Boolean(nullable: false),
Firmatecknare = c.Boolean(nullable: false),
Registreringsanmalan = c.Boolean(nullable: false),
FirmatecknareGeneralfullmakt = c.Boolean(nullable: false),
Revisor = c.Boolean(nullable: false),
})
.PrimaryKey(t => new { t.ParentIntressentId, t.ChildIntressentId })
.ForeignKey("dbo.Intressent", t => t.ParentIntressentId)
.ForeignKey("dbo.Intressent", t => t.ChildIntressentId)
.ForeignKey("dbo.Intressent", t => t.ParentIntressentId)
.ForeignKey("dbo.Intressent", t => t.ChildIntressentId)
.Index(t => t.ParentIntressentId)
.Index(t => t.ChildIntressentId)
.Index(t => t.ParentIntressentId)
.Index(t => t.ChildIntressentId);
我的课是这样的。如果我在 onmodelCreating EF 中删除 fk 语句,将为我添加它。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Entity<Entity.IntressentIntressent>().HasKey(k => new
{k.ParentIntressentId, k.ChildIntressentId });
modelBuilder.Entity<Entity.Intressent>().HasMany(c => c.ParentIntressenter)
.WithRequired().HasForeignKey(cp => cp.ParentIntressentId);
modelBuilder.Entity<Entity.Intressent>().HasMany(p => p.ChildIntressenter)
.WithRequired().HasForeignKey(cp => cp.ChildIntressentId);
}
实体看起来像这样
public class Intressent
{
private ObservableCollection<IntressentIntressent> _parentIntressenter;
public virtual ObservableCollection<IntressentIntressent> ParentIntressenter
{
get { return _parentIntressenter ?? (_parentIntressenter = new
ObservableCollection<IntressentIntressent>()); }
set { _parentIntressenter = value; }
}
}
public class IntressentIntressent
{
[DisplayName("ParentIntressentId")]
[Description("ParentIntressentId")]
[Key, ForeignKey("ParentIntressent")]
public int ParentIntressentId { get; set; }
[DisplayName("ChildIntressentId")]
[Description("ChildIntressentId")]
[Key, ForeignKey("ChildIntressent")]
public int ChildIntressentId { get; set; }
[ForeignKey("ParentIntressent")]
public Intressent ParentIntressent { get; set; }
[ForeignKey("ChildIntressent")]
public Intressent ChildIntressent { get; set; }
[Required]
[DisplayName("Aktieantal")]
[Description("Aktieantal")]
public int Aktieantal { get; set; }
}