Entity Framework Core change entity relation before SaveChanges

c# entity-framework-core

Question

Is there a method to change entity relationships before making a general SaveChanges call?

public class Vehicle
{
    public int Id { get; set; }
    public int OwnerId { get; set; }
    [ForeignKey("OwnerId")]
    public Person Owner { get; set; }
}

For instance, I want to create a new Person and add it to a vehicle before an ID is created (before calling SaveChanges). I am confident in my ability to:

entry.Property("OwnerId").CurrentValue = newId;

However, the issue is that I wasn't aware of the new entity's Id before calling.SaveChanges .

In order to do what I'm aiming for, once the Owner changes, I want to immediately make a duplicate of it and assign the Owner to it. Without a doubt, I must carry out the task within the SaveChanges override.

the following

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);
}

How I hope it will operate

//would insert new Person row and update OwnerId to point to this new row
vehicle.Owner.Name = "NewName";
1
0
5/2/2018 2:33:26 PM

Accepted Answer

ZZZ_tmp
2
5/2/2018 2:45:25 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow