Skip to content

Fix exception propagation #1021

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

Merged
merged 7 commits into from
Jun 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ protected virtual async Task SaveChangesAsync(CancellationToken cancellationToke
{
await _dbContext.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException exception)
catch (Exception exception) when (exception is DbUpdateException || exception is InvalidOperationException)
{
if (_dbContext.Database.CurrentTransaction != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,15 @@ private void Detach(IEnumerable<object> resources)
{
foreach (object resource in resources)
{
_dbContext.Entry(resource).State = EntityState.Detached;
try
{
_dbContext.Entry(resource).State = EntityState.Detached;
}
catch (InvalidOperationException)
{
// If SaveChanges() threw due to a foreign key constraint violation, its exception is rethrown here.
// We swallow this exception, to allow the originating error to propagate.
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<MusicTrack>()
.HasOne(musicTrack => musicTrack.Lyric)
.WithOne(lyric => lyric.Track)
.HasForeignKey<MusicTrack>();
.HasForeignKey<MusicTrack>("LyricId");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<Building>()
.HasOne(building => building.PrimaryDoor)
.WithOne()
.HasForeignKey<Building>("PrimaryDoorKey")
.HasForeignKey<Building>("PrimaryDoorId")
.IsRequired();

builder.Entity<Building>()
.HasOne(building => building.SecondaryDoor)
.WithOne()
.HasForeignKey<Building>("SecondaryDoorKey")
.HasForeignKey<Building>("SecondaryDoorId")
.IsRequired(false);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<Photo>()
.HasOne(photo => photo.Location)
.WithOne(location => location.Photo)
.HasForeignKey<Photo>("PhotoLocationKey");
.HasForeignKey<Photo>("LocationId");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<WorkItemGroup>()
.HasOne(workItemGroup => workItemGroup.Color)
.WithOne(color => color.Group)
.HasForeignKey<RgbColor>();
.HasForeignKey<RgbColor>("GroupId");

builder.Entity<WorkItemTag>()
.HasKey(workItemTag => new
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,14 @@ protected override void OnModelCreating(ModelBuilder builder)
.WithOne(order => order.Customer)
.IsRequired();

// By default, EF Core generates an identifying foreign key for a required 1-to-1 relationship.
// This means no foreign key column is generated, instead the primary keys point to each other directly.
// That mechanism does not make sense for JSON:API, because patching a relationship would result in
// also changing the identity of a resource. Naming the key explicitly forces to create a foreign key column.
builder.Entity<Order>()
.HasOne(order => order.Shipment)
.WithOne(shipment => shipment.Order)
.HasForeignKey<Shipment>()
.HasForeignKey<Shipment>("OrderId")
.IsRequired();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Serialization.Objects;
using JsonApiDotNetCoreExampleTests.Startups;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
Expand Down Expand Up @@ -113,12 +114,12 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
string route = $"/customers/{existingOrder.Customer.Id}";

// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route);
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);

// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

responseDocument.Should().BeNull();
responseDocument.Should().BeEmpty();

await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Expand Down Expand Up @@ -147,12 +148,12 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
string route = $"/orders/{existingOrder.Id}";

// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route);
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);

// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

responseDocument.Should().BeNull();
responseDocument.Should().BeEmpty();

await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Expand Down Expand Up @@ -382,7 +383,7 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
}

[Fact]
public async Task Cannot_reassign_dependent_side_of_OneToOne_relationship_with_identifying_foreign_key_through_primary_endpoint()
public async Task Can_reassign_dependent_side_of_ZeroOrOneToOne_relationship_through_primary_endpoint()
{
// Arrange
Order orderWithShipment = _fakers.Orders.Generate();
Expand Down Expand Up @@ -421,21 +422,24 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
string route = $"/orders/{orderWithoutShipment.Id}";

// Act
(HttpResponseMessage httpResponse, ErrorDocument responseDocument) = await _testContext.ExecutePatchAsync<ErrorDocument>(route, requestBody);
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.InternalServerError);
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

responseDocument.Errors.Should().HaveCount(1);
responseDocument.Should().BeEmpty();

Error error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
error.Title.Should().Be("An unhandled error occurred while processing this request.");
error.Detail.Should().StartWith("The property 'Id' on entity type 'Shipment' is part of a key and so cannot be modified or marked as modified.");
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Shipment existingShipmentInDatabase =
await dbContext.Shipments.Include(shipment => shipment.Order).FirstWithIdOrDefaultAsync(orderWithShipment.Shipment.Id);

existingShipmentInDatabase.Order.Id.Should().Be(orderWithoutShipment.Id);
});
}

[Fact]
public async Task Cannot_reassign_dependent_side_of_OneToOne_relationship_with_identifying_foreign_key_through_relationship_endpoint()
public async Task Can_reassign_dependent_side_of_ZeroOrOneToOne_relationship_through_relationship_endpoint()
{
// Arrange
Order orderWithShipment = _fakers.Orders.Generate();
Expand Down Expand Up @@ -463,17 +467,20 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
string route = $"/orders/{orderWithoutShipment.Id}/relationships/shipment";

// Act
(HttpResponseMessage httpResponse, ErrorDocument responseDocument) = await _testContext.ExecutePatchAsync<ErrorDocument>(route, requestBody);
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.InternalServerError);
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

responseDocument.Errors.Should().HaveCount(1);
responseDocument.Should().BeEmpty();

Error error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
error.Title.Should().Be("An unhandled error occurred while processing this request.");
error.Detail.Should().StartWith("The property 'Id' on entity type 'Shipment' is part of a key and so cannot be modified or marked as modified.");
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Shipment existingShipmentInDatabase =
await dbContext.Shipments.Include(shipment => shipment.Order).FirstWithIdOrDefaultAsync(orderWithShipment.Shipment.Id);

existingShipmentInDatabase.Order.Id.Should().Be(orderWithoutShipment.Id);
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<Passport>()
.HasOne(passport => passport.Person)
.WithOne(person => person.Passport)
.HasForeignKey<Person>("PassportKey")
.HasForeignKey<Person>("PassportId")
.OnDelete(DeleteBehavior.SetNull);
}
}
Expand Down
4 changes: 2 additions & 2 deletions test/UnitTests/ResourceHooks/HooksDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<Passport>()
.HasOne(passport => passport.Person)
.WithOne(person => person.Passport)
.HasForeignKey<Person>("PassportKey")
.HasForeignKey<Person>("PassportId")
.OnDelete(DeleteBehavior.SetNull);

builder.Entity<TodoItem>()
.HasOne(todoItem => todoItem.OneToOnePerson)
.WithOne(person => person.OneToOneTodoItem)
.HasForeignKey<TodoItem>("OneToOnePersonKey");
.HasForeignKey<TodoItem>("OneToOnePersonId");
}
}
}