EF Core - Obtain new Ids after upsert, then use them to add new entity to database

Viewed 166

I'm trying to use this function from SO to add an entity to the database if it doesn't exist:

public static class DbSetExtensions
{
    public static EntityEntry<T> AddIfNotExists<T>(this DbSet<T> dbSet, T entity, Expression<Func<T, bool>> predicate = null) where T : class, new()
    {
        var exists = predicate != null ? dbSet.Any(predicate) : dbSet.Any();
        return !exists ? dbSet.Add(entity) : null;
    }
}

To add a join table entity into the database straight after adding the two single table entities (which will be assigned new Ids upon insertion). I am using FlexLabs Upsert to insert/update depending on if they already exist for the two single table entities:

[HttpPost]
public async Task<ActionResult<GroceryItemGroceryStore>> PostGroceryItemGroceryStore(GroceryItemGroceryStore groceryItemGroceryStore)
{
    
    await _context.GroceryItems.Upsert(groceryItemGroceryStore.VeganItem).On(v => new { v.Name, v.Brand }).RunAsync();
    await _context.GroceryStores.Upsert(groceryItemGroceryStore.Establishment).On(c => c.PlaceId).RunAsync();
    _context.SaveChanges();
    
    _context.Set<GroceryItemGroceryStore>().AddIfNotExists(groceryItemGroceryStore , x => x.VeganItemId == x.VeganItemId && x.EstablishmentId == x.EstablishmentId);
    

    try
    {
        await _context.SaveChangesAsync();
    }

However, the x.VeganItemId and x.EstablishmentId are still 0 when trying to add the join entity to the database, as I am not obtaining the new Ids after the first two adds to the database. How do I obtain their newly added Ids from the Upsert executions and then use them with AddIfNotExists to insert the new Join Entity if one does not exist with a VeganItemId of the new VeganItem.Id and EstablishmentId of the new Establishment.Id?

0 Answers
Related