Don't fail silently when meeting data that breaks a defined relationship

Open
#19,868 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Stale
Tech stack
csharp
Domain
backend, databases

Research direction

Start by reproducing the one-to-one relationship with duplicate foreign-key values and observe how EF Core marks duplicates in the change tracker. Check the behavior before and after SaveChangesAsync; done should mean inconsistent relationship data is not silently treated as deleted, with the resulting handling made explicit.

Written by the indexing model from the issue text.

Description

area-query customer-reported

I'll explain with an example (which is how I learnt of this):

Let's say you define a one-to-one relationship between data in two tables, such as below.

entity.HasOne(typeof(User), nameof(BaseEntity.UserCreated))
    .WithOne()
    .HasForeignKey(entityType.ClrType, nameof(BaseEntity.UserCreatedID));

entity.HasOne(typeof(User), nameof(BaseEntity.UserUpdated))
    .WithOne()
    .HasForeignKey(entityType.ClrType, nameof(BaseEntity.UserUpdatedID));

You then retrieve a collection of the data containing the foreign key, and it turns out multiple entities in that table has the same foreign-key. The way EF Core seems to handle this is to mark duplicates as deleted in the change tracker, and then it moves on.

It makes sense that this doesn't work as expected, as the relationships defined in EF Core doesn't match the real data. BUT it shouldn't fail silently, and it definitely shouldn't just track 'duplicates' as deleted. One call to DBContext.SaveChangesAsync(), and that data is gone.

I'm not sure if the appropriate response would be to throw an exception, but I think it's wrong to just manipulate the data so that the relationships are still true. Very open to suggestions about how such a situation may be handled better.

I obviously got into this situation because I mistakenly defined my relationship as a one-to-one relationship instead of one-to-many. But it'd be nice if EF Core helped me discover that mistake, instead of silently 'fixing' the issue.

Dominant language
C#
Stars
14.8k
Forks
3.4k
Avg merge
2d 5h
Merged PRs (30d)
134

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/efcore

All issues in dotnet/efcore

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.