© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
65 replies
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)
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>()
};
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!;
    public int? EntityId { get; set; }
    [ForeignKey(nameof(EntityId))] public EFEntity? Entity { get; set; } = null!;
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

✅ Circular References
C#CC# / help
2y ago
Puzzled about Nullability in EFCore
C#CC# / help
14mo ago
Entity Framework - Circular References
C#CC# / help
2y ago
Avoiding circular references in navigation properties
C#CC# / help
2y ago