如何创建具有自引用EFCore的模型

问题描述 投票:0回答:1

我创建一个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”中。

c# code-first ef-fluent-api self-reference ef-core-2.1
1个回答
0
投票

请尝试将OnModelCreating更改为

 .HasForeignKey(entity => entity.TagMotherID);
© www.soinside.com 2019 - 2024. All rights reserved.