I have the following code-first models:
public abstract class BaseEntity
{
public int Id { get; set; }
}
public class Field : BaseEntity
{
public string Value { get; set; }
public Component Component { get; set; }
public string Status { get; set; }
public Field() { }
public Field(string value, Component component, string status = null)
{
Value = value;
Component = component;
Status = status;
}
}
public class Component : BaseEntity
{
public string Title { get; set; }
[ForeignKey("SmartObject")]
public int? SmartObjectId { get; set; }
public Component SmartObject { get; set; }
[ForeignKey("Parent")]
public int? ParentId { get; set; }
public Component Parent { get; set; }
public ComponentType Type { get; set; }
public virtual ICollection<Field> Fields { get; set; }
public IList<QueryComponent> Queries { get; set; }
public IList<ReportComponent> Reports { get; set; }
}
and the following logic (here written in pseudo-code, possible that I missed something, in which case - apologies):
public class SampleClass
{
IFieldRepository _fieldRepository;
public SampleClass(IFieldRepository fieldRepository)
{
_fieldRepository = fieldRepository;
}
public void UpdateStatus()
{
var fieldList = _fieldRepository.GetById(3);
foreach (var item in updateFVList_Formatted)
{
item.Status = "new";
_fieldRepository.DisableChange(item);
}
}
}
public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : BaseEntity
{
internal ApplicationDBContext _context;
internal DbSet<TEntity> _entity;
public BaseRepository(ApplicationDBContext context)
{
_context = context;
_entity = _context.Set<TEntity>();
}
public void GetById(int ID)
{
return _entity.Where(x => x.Id == ID).ToList();
}
public void DisableChange(Field field)
{
_context.Entry(field).State = EntityState.Unchanged;
_context.Entry(field.Component).State = EntityState.Unchanged;
}
}
Here the "UpdateStatus" method is being called.
The issue I have and the reason for the "DisableChange" method is that EF Core decides that the "Component" property has been changed or something and when changes are saved, no matter what I do that has nothing to do with "Component" - EF Core updates the "Component" table in the database and sets its "ParentId" property to NULL, along with any other actual changes.
So for example with the following pseudo code, if the call to "DisableChanges" is omitted and I just call DbContext.SaveChanges(), EF Core updates the entries in the "Field" table AND the "ParentId" column of the "Component" table.
I tried telling EF Core "Component" is not changed via the "DisableChange" method but all that did was omit the update clause for the entries in the "Field" table. Resulting in a single UPDATE to the "Component" table.
I can't figure out why this is happening and how to prevent it. I want EF Core to ONLY update the "Field" items that I actually change.