在以通用方式调用SaveChanges之前,有什么方法可以更新实体关系?
public class Vehicle
{
public int Id { get; set; }
public int OwnerId { get; set; }
[ForeignKey("OwnerId")]
public Person Owner { get; set; }
}
例如,我想创建一个新的Person,并在生成ID之前将其分配给Vehicle(在调用SaveChanges之前)。我知道我可以这样做:
entry.Property("OwnerId").CurrentValue = newId;
但是问题在于在调用之前我不知道新实体的ID SaveChanges。
我要实现的是在更改时自动创建所有者的副本,并将所有者分配给该副本。当然,我必须在SaveChanges覆盖内以某种方式执行此操作。
就像是:
public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
foreach (var entry in ChangeTracker.Entries())
{
foreach (var reference in entry.References)
{
if (reference.TargetEntry != null && reference.TargetEntry.State == EntryState.Modified)
{
// make a copy of target entry and update reference to it,
// note: you can't really add new entries inside this loop as it will throw an exception, so all the adding has to be done outside
// I would like to set this newEntity as the Owner
var newEntity = (BaseEntity)entry.CurrentValues.ToObject();
newEntity.Id = 0;
}
}
}
return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
我希望它如何工作:
//would insert new Person row and update OwnerId to point to this new row
vehicle.Owner.Name = "NewName";
繁星点点滴滴
相关分类