© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
8 replies
Core

EF navigation property is unattached from dbContext

Hello!
There are 2 Entities in relation with each other:
User
User
and
Domain
Domain
. When I want to insert a new Domain to the database an exception will occur, because the User related to it is not tracked.

There are 2 solutions, but I cannot decide which one is better.

1. Do an extra query to get the User:
domain.User = userRepo.FindUser(userId)
domain.User = userRepo.FindUser(userId)

2. Write an extra class that attaches the user to the context:
extraClass.AttachToDbContext(new User(userId))
extraClass.AttachToDbContext(new User(userId))
- no extra query performed (User already exists in the database)

I like the 2nd option better, but would like to hear other opinions

public class User
{
    public string UserId { get; set; }
}

public class Domain
{
    public Guid DomainId { get; set; }
    public string DomainName { get; set; }

    public User User { get; set; }
}
public class User
{
    public string UserId { get; set; }
}

public class Domain
{
    public Guid DomainId { get; set; }
    public string DomainName { get; set; }

    public User User { get; set; }
}
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

Similar Threads

✅ Transient DbContext vs DbContextFactory
C#CC# / help
2y ago
✅ EF Core, Proper DbContext Instantiation
C#CC# / help
3y ago
✅ Navigation Property
C#CC# / help
2y ago