Home > database >  How does EF update 'parentId' that has relationship parent-child in single table?
How does EF update 'parentId' that has relationship parent-child in single table?

Time:12-15

My Model Class is:

public class Department
{
    [Key]
    public long Id { get; set; }

    [Required]
    public string DepartmentName { get; set; }

    public virtual Department Parent { get; set; }
    public long? ParentId { get; set; }
    public virtual ICollection<Department> SubDepartments { get; set; }

}

DbContext is:

public class MyDbContext : DbContext
{
    public DbSet<Department> Departments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Department>()
            .HasMany(s => s.SubDepartments)
            .WithOptional(s => s.Parent)
            .HasForeignKey(s => s.ParentId);


        base.OnModelCreating(modelBuilder);
    }
}

Updating like this:

var result = GetSubDepartmentList();
for (int i = 0; i < result.Count; i  )
{
    result.DepartmentName = "Name";
    result.ParentId = 3;
}
db.SaveChanges();

My definitions are like this. EF is updating other fields except 'parentId'. How can i update 'parentId' ?

CodePudding user response:

Based on your comment, you might have to query DB in the loop. Something like:

var result = GetSubDepartmentList();
for (int i = 0; i < result.Count; i  )
{
    var department = db.Departments.FirstOrDefault(a => a.Id == result[i].Id);
    if(department != null)
    {
        department.DepartmentName = "Name";
        department.ParentId = 3;
        db.SaveChanges();
    }
}
  • Related