Skip to content

DbUpdateConcurrencyException when creating resources with relationships with ConcurrencyStamp #350

Closed
@jaredcnance

Description

@jaredcnance

Currently, if you try to create a resource with a HasOne relationship to an object that has a ConcurrencyStamp property via the EF .IsConcurrencyToken() method you will likely get a DbUpdateConcurrencyException thrown. Many of the ASP.Net Core Identity classes have this concurrency check.

See this for details: dotnet/efcore#9166 (comment)

As a workaround, you need to identify the resources that enforce the concurrency check and manually fetch them from the database. You also need to prevent JADNC from attaching the relationship pointer. So, change this:

public virtual async Task<TEntity> CreateAsync(TEntity entity)
{
AttachRelationships();
_dbSet.Add(entity);
await _context.SaveChangesAsync();
return entity;
}

To something along the lines of this:

public override async Task<Relationship> CreateAsync(Relationship relationship)
{
    // this would need to implement something similar to the default
    // implementation, excluding any relationships that include the 
    // concurrency stamp
    AttachOtherRelationships();

    if (relationship.Role == null)
        throw new JsonApiException(400, "Cannot create relationship without a Role");

    var role = await _context.Roles.SingleOrDefaultAsync(r => r.Id == relationship.Role.Id);
    if (role == null)
        throw new JsonApiException(400, $"Role '{relationship.Role?.Id}' does not exist");

    // manually assign the Role
    relationship.Role = role;

    _relationships.Add(relationship);
    await _context.SaveChangesAsync();
    return relationship;
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions