在SaveChanges之前的实体框架核心更改实体关系

在以通用方式调用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";


长风秋雁
浏览 142回答 1
1回答

繁星点点滴滴

您应该更新引用,以便在没有ID时更新ID:public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken)){&nbsp; &nbsp; foreach (var entry in ChangeTracker.Entries())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;bool shouldUpdateReference = false;&nbsp; &nbsp; &nbsp; &nbsp;foreach (var reference in entry.References)&nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (reference.TargetEntry != null && reference.TargetEntry.State == EntryState.Modified)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;shouldUpdateReference = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; // I imagine this has to be done outside the foreach&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // since you are modifying a reference and that should&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // update the References collection&nbsp; &nbsp; &nbsp; &nbsp; if (shouldUpdateReference)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; entity.Reference("Owner").CurrentValue = newOwner;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);}
打开App,查看更多内容
随时随地看视频慕课网APP