我正在尝试在具有相关数据的根实体上以一对多导航属性的形式实现跟踪元数据。该根实体的元数据取决于对其自身和任何相关实体的更改。我有一个存储库,该存储库将通过DbContext的更改跟踪器检测更改,但仅在 root 实体本身被修改时才检测,而在子实体发生更改时才检测。每当子实体被标记为已修改时,是否可以通过某种方法使EF将相应的根实体也标记为已修改?对子实体的所有更改都是通过根实体方法进行的,因此始终会加载相应的根。
public class Root: ITrackingData
{
public int Id {get; set;}
public virtual ICollection<Child> Children{get; set;}
public object ModfiedMetadata{get; set;}
public object CreatedMetadata{get; set;}
...
public void AddChild(Child child)
{
Children.add(child);
}
}
public class Child
{
public int Id {get; set;}
public string Name {get; set;}
public Root Root {get; set;
public int RootId {get; set;}
public Child(string name) { Name = name; }
}
public class Repo
{
public DbContext context;
...
public Root Create()
{
var root = context.Roots.Create();
...
return root;
}
public Root GetById(int id)
{
return context.Roots
.Include(e=>e.Children)
.FirstOrDefault(e=>e.Id==id);
}
public void Save()
{
foreach (var change in _context.ChangeTracker.Entries())
{
if (change.Entity is ITrackingData metadata)
{
if (change.State == EntityState.Added)
{
metadata.ModfiedMetadata = <stuff>;
metadata.CreatedMetadata = <more stuff>;
}
else if (change.State == EntityState.Modified)
{
metadata.ModfiedMetadata= <new stuff>;
}
}
}
}
}
我正在使用fluent API来配置以下关系:
model.Entity<Child>()
.HasRequired(e => e.Root)
.WithMany(e => e.Child)
.HasForeignKey(e => e.RootId);
如果我查找一个根项目并将其添加到其Childs集合中,则该根实体永远不会被标记为“已修改”,因此不会更新其跟踪数据。
var root = repo.GetById(1);
root.AddChild(new Child("new child"));
repo.Save();
//root.ModifiedMetadata is still the same as when it was created