实体框架将实体更新为自引用

时间:2019-06-18 03:16:58

标签: entity-framework-core

我试图用本质上两个类为图节点集合建模。一个保存节点属性,另一个保存节点之间的关系。

节点代码如下:

[Table("Classes")]
public class Class
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public int CreditValue { get; set; }
    public string LongName { get; set; }
    public string ShortName { get; set; }
    public bool IsCompleted { get; set; }

    public virtual List<Prerequisite> Prerequisites { get; set; }
    public virtual ICollection<PlanClass> PlanClasses { get; set; }
    public virtual List<Prerequisite> RefPrerequisites { get; set; }
}

关系是Prerequisite类:

    [Key]
    public Guid Id { get; set; }

    public Guid ClassToId { get; set; }

    [ForeignKey("ClassToId")]
    public Class ClassTo { get; set; }

    public Guid ClassFromId { get; set; }

    [ForeignKey("ClassFromId")]
    public Class ClassFrom { get; set; }

    public bool IsSoft { get; set; }

    public virtual List<Flag> OtherRequirements { get; set; }

我的DbContext如下:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Class>().HasMany(e=>e.Prerequisites).WithOne();
        modelBuilder.Entity<Class>().HasMany(e => e.RefPrerequisites).WithOne();
        modelBuilder.Entity<Prerequisite>()
            .HasOne(e => e.ClassFrom)
            .WithMany(e => e.Prerequisites)
            .HasForeignKey(e => e.ClassFromId);
        modelBuilder.Entity<Prerequisite>()
            .HasOne(e => e.ClassTo)
            .WithMany(e => e.RefPrerequisites)
            .HasForeignKey(e=>e.ClassToId).OnDelete(DeleteBehavior.Restrict);
        modelBuilder.Entity<PlanClass>()
    .       HasKey(bc => new { bc.ClassId, bc.PlanId });
        modelBuilder.Entity<PlanClass>()
            .HasOne(bc => bc.Class)
            .WithMany(b => b.PlanClasses)
            .HasForeignKey(bc => bc.ClassId);
        modelBuilder.Entity<PlanClass>()
            .HasOne(bc => bc.Plan)
            .WithMany(c => c.PlanClasses)
            .HasForeignKey(bc => bc.PlanId);
    }

我尝试设置多对多关系,并且似乎正确填充了该关系,只是在db.update(entity)上,引用才成为自引用。

Prerequisite classExists = new Prerequisite
 {
      ClassToId = classToAdd.Id,
      ClassFromId = classToCompare.Id,
      EquivalentReqs = new List<Class>(),
      IsSoft = false,
      OtherRequirements = new List<Flag>()
 };

classExists = db.Add(classExists).Entity;
db.SaveChanges();
prerequisites.Add(classExists);
...
classToAdd.Prerequisites = prerequisites;
db.Update(classToAdd); // This is where the prerequisites class is populated with the same object for class from and class to.
db.SaveChanges();

before db.SaveChanges()

after db.SaveChanges()

0 个答案:

没有答案