我创建一个wpf应用程序,我使用entityFrameworkCore创建数据库,但我无法创建具有自引用的模型。我尝试了所有的选择
我的模特
public class Tag
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TagID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int TagLevel { get; set; }
public int? TagMotherID { get; set; }
public virtual Tag TagMother { get; set; }
public virtual ICollection<Tag> ListOfTagsChild { get; set; }
public virtual ICollection<ArchiveTag> ListOfArchive { get; set; }
}
并在OnModelCreating方法
modelBuilder.Entity<Tag>()
.HasOne(entity => entity.TagMother)
.WithMany(entity => entity.ListOfTagsChild)
.HasForeignKey(entity => entity.TagMotherID);
标签可以有一个或零个父级,但他可以有很多孩子
有这个我有这个错误
SqlException:MERGE语句与FOREIGN KEY SAME TABLE约束“FK_Tags_Tags_TagMotherID”冲突。冲突发生在数据库“EFCoreTest”,表“dbo.Tags”,列“TagID”中。
请尝试将OnModelCreating更改为
.HasForeignKey(entity => entity.TagMotherID);