EF Core 第二个对象引用生成循环依赖

EF Core second object reference generates circular dependency

第二个class不能有第二个引用吗? FirstClass 包含 SecondClasses,SeocondBegin 包含开始元素。使用此代码,我在 SaveChanges 中获得了执行:

System.InvalidOperationException: 'Unable to save changes because a circular dependency was detected in the data to be saved: 'FirstClass { 'Id': -2147482647 } [Added] <-
SecondClasses FirstClass { 'FirstClassId': -2147482647 } SecondClass { 'Id': -2147482647 } [Added] <-
SecondBegin { 'SecondBeginId': -2147482647 } FirstClass { 'Id': -2147482647 } [Added]'.'

我想要这个 属性 因为第二个 class 应该是 'linked list' 并且 SecondClasses 集合不包含 来源是:

namespace EFTestApp
{
    public class FirstClass
    {
        public int Id { get; set; }
        public int? SecondBeginId { get; set; }
        public string Name { get; set; }
        [ForeignKey(nameof(SecondBeginId))]
        public SecondClass SecondBegin { get; set; }
        [InverseProperty(nameof(EFTestApp.SecondClass.FirstClass))]
        [IgnoreDataMember]
        public ICollection<SecondClass> SecondClasses { get; set; }
    }
}

namespace EFTestApp
{
    public class SecondClass
    {
        public int Id { get; set; }
        public int FirstClassId { get; set; }
        public string Url { get; set; }
        [ForeignKey(nameof(FirstClassId))]
        public FirstClass FirstClass { get; set; }
        public SecondClass Next { get; set; }
    }
}

namespace EFTestApp
{
    public class ApplicationDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.EnableSensitiveDataLogging();
            optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=sample;Trusted_Connection=True");
        }

        public DbSet<FirstClass> FirstClasses { get; set; }
        public DbSet<SecondClass> SecondClasses { get; set; }
    }
}

namespace EFTestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbContext = new ApplicationDbContext();
            dbContext.Database.EnsureCreated();

            var firstClass = new FirstClass()
            {
                Name = "First"
            };
            var secondClass = new SecondClass()
            {
                FirstClass = firstClass,
                Url = "Blablah"
            };
            
            firstClass.SecondBegin = secondClass;

            dbContext.Add(firstClass);
            dbContext.SaveChanges();
        }
    }
}

有一个循环很好,但是您不能通过一次调用 SaveChanges() 来创建它,因为 EF 无法在没有另一行的情况下插入任何一行。

您必须在此处调用两次 SaveChanges,一次用于插入实体,然后再次用于“关闭”循环。

例如

dbContext.Add(firstClass);
dbContext.Add(secondClass);
dbContext.SaveChanges();

firstClass.SecondBegin = secondClass;
dbContext.SaveChanges();