简体   繁体   中英

EF Core and referencing the ID of a entity before calling SaveChangesAsync()

I have a scenario where I want to add an entity (say EntityA), but I also want to add details of this entity, including the auto-generated ID, to an Outbox entity, before calling SaveChanges(). This is so I can have both inserts wrapped within the same transaction.

The Outbox entity has a field called AggregateId and is of type string .

The auto-generated ID field of EntityA is of type long .

Basically every time I insert/update EntityA (or EntityB, EntityC, etc), I want to also add an Outbox entity.

What I can't work out is, how to do this so that when both EntityA, and the Outbox entity are saved, the AggregateId is populated with the newly generated ID of EntityA.

var entityA = new EntityA()
{
   // public long Id { get; set; }  //-- Auto-generated
   // set other properties ...
};
_context.Entities.Add(entityA);

var outbox = new Outbox()
{
   AggregateType = nameof(EntityA),
   AggregateId = entityA.Id.ToString()
};
_context.Outboxes.Add(outbox);

// I even tried ...
// outbox.AggregateId = entityA.Id.ToString();

await _context.SaveChangesAsync();

I don't think it is a foreign key set up I'm after because AggregateId could refer to EntityA, EntityB, etc, but I could be wrong.

Is there a way to set up a one-way relationship in EF Core so that EntityA refers to a ICollection<Outbox> Outboxes but maps the Id( long ) to AggregateId( string ), therefore allowing me to do ...

entityA.Outboxes.Add(outbox);

If you construct the backing class correctly then everything works. You do not need any Id property. EF itself constructs the correct int EntityAId foreign key relationship

public class EntityA
{
    ...
    public ICollection<EntityB> SetOfBs { get; set; }
}

public class EntityB
{
    ...
    public EntityB EntityA { get; set; }
}


var a = new EntityA();
var b = new EntityB() { EntityA = a };

context.Bs.Add(a)
context.SaveChangesAsync();

The response from @jeremy-lakeman was the answer to this problem ( https://stackoverflow.com/a/69356696/4139809 ).

But I did need to add another field to my outbox entity, that was the same type as the entity Id. I couldn't get it to work when the Id of my entity was, say, a long , and the foreign key field was a string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM