如果我(首先在代码中)定义了一个导航属性给自己,它就可以工作(创建外键),但如果我定义 2,它就不起作用。
如何为自己创建 2 个外键? 基于 documentation按照惯例,它们应该被创建。
例如这有效(创建外键):
public class DbPart
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("Source")]
public int? SourceId { get; set; }
public DbPart Source { get; set; }
[InverseProperty("Source")]
public List<DbPart> SourceParts { get; set; }
}
这是这样的:
public class DbPart
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("SourceFake")]
public int? SourceFakeId { get; set; }
public DbPart SourceFake { get; set; }
[InverseProperty("SourceFake")]
public List<DbPart> SourceFakeParts { get; set; }
}
但不是这个:
public class DbPart
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("Source")]
public int? SourceId { get; set; }
public DbPart Source { get; set; }
[ForeignKey("SourceFake")]
public int? SourceFakeId { get; set; }
public DbPart SourceFake { get; set; }
[InverseProperty("SourceFake")]
public List<DbPart> SourceFakeParts { get; set; }
[InverseProperty("Source")]
public List<DbPart> SourceParts { get; set; }
}
我还有一个例子,我在数据库中写了树结构,但是我只写了ParentId,我也写了RootId。同样,在将 2 个属性(ParentId、RootId)引用到自身时不会创建外键。
已编辑:
由于 this 而无法正常工作漏洞。简单的解决方案是从 Id 属性中删除 [Key] 或在 Steve Greene 回答中使用流畅的解决方案。也检查 here .
最佳答案
对于这些东西,我更喜欢流畅的代码:
modelBuilder.Entity<DbPart>()
.HasOne(p => p.Source)
.WithMany(p => p.SourceParts)
.HasForeignKey(p => p.SourceId);
modelBuilder.Entity<DbPart>()
.HasOne(p => p.SourceFake)
.WithMany(p => p.SourceFakeParts)
.HasForeignKey(p => p.SourceFakeId);
但是如果你想要注释试试这个:
public class DbPart
{
public int Id { get; set; } // Key & Indentity by convention
public int? SourceId { get; set; } // FK by convention
[InverseProperty("SourceParts")]
public DbPart Source { get; set; }
public int? SourceFakeId { get; set; } // FK by convention
[InverseProperty("SourceFakeParts")]
public DbPart SourceFake { get; set; }
[InverseProperty("SourceFake")]
public List<DbPart> SourceFakeParts { get; set; }
[InverseProperty("Source")]
public List<DbPart> SourceParts { get; set; }
}
关于entity-framework - 如果自身有 2 个外键,EF Core 自引用不起作用(代码优先),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46827795/