C#C
C#3y ago
Amos

✅ EFCore Nullability and Circular References

I have 2 tables which have FK's to each other due to the relationship.

I'm trying to add some seed data for a profile that needs to be created on initialisation.
EFUser(single - FK to most recent EFAlias) -> EFAlias(many - FK to EFUser)

EFAlias(many - FK to EFUser) -> EFUser(single - FK to most recent EFAlias)

I've tried two ways...

  1. I'm getting an SQL 19 error which is a expected field that isn't provided (NULL). If I set the FK in EFAlias to Nullable with ?, then the field in the database isn't populated (which makes sense). However, with the above scenario if I ever lookup the seeded user from their EFAlias, FK to EFUser isn't populated. So it's not possible.
  2. If I remove the Nullable statement in the property and provide the UserId and AliasId in the seed data, the migration fails due to Circular Reference (which again, makes sense)
Is there a way I can both have each field populated and required (not nullable)?

Prefixed tables with EF just to make it a little clearer.

SEED: (2nd example - circular reference)
var adminAlias = new EFAlias
{
    Id = 1,
    EntityId = 1, 
    UserName = "IW4MAdmin",
    IpAddress = "0.0.0.0",
    Changed = DateTimeOffset.UtcNow
};

var adminEntity = new EFEntity
{
    Id = 1,
    CurrentAliasId = 1,
    ProfileIdentity = "0:UKN",
    Reputation = 0,
    Infractions = new List<EFInfraction>()
};

MODEL: (1st example - missing FK in EFAlias)
    public int? EntityId { get; set; }
    [ForeignKey(nameof(EntityId))] public EFEntity? Entity { get; set; } = null!;
Was this page helpful?