Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DbUpdateConcurrencyException when creating resources with relationships with ConcurrencyStamp #350

Closed
jaredcnance opened this issue Jul 23, 2018 · 1 comment

Comments

@jaredcnance
Copy link
Contributor

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants