I am using MassTransit Outbox feature. I often get exception like this
EntityFramework.Exceptions.Common.ReferenceConstraintException: Reference constraint violation ---> Npgsql.PostgresException (0x80004005): 23503: update or delete on table "InboxState" violates foreign key constraint "FK_OutboxMessage_InboxState_InboxMessageId_InboxConsumerId" on table "OutboxMessage"
.
When this is happening I have to explicitly remove messages from tables. How to avoid getting this error ?
Here Is config code snippet.
busConfig.AddEntityFrameworkOutbox<AppDbContext>(outboxConfig =>
{
outboxConfig.UsePostgres();
outboxConfig.UseBusOutbox();
outboxConfig.QueryMessageLimit = 50;
outboxConfig.DuplicateDetectionWindow = TimeSpan.FromMinutes(1);
});
After some research I found out that, the QueryTrackingBehavior of Entity Framework was QueryTrackingBehavior.NoTracking
which caused problems. After turning the tracking behavior into QueryTrackingBehavior.TrackAll
, all problems gone.
services.AddDbContext<AppDbContext>((sp, opt) =>
{
opt.UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll);
//...
});