C#C
C#3y ago
Core

EF navigation property is unattached from dbContext

Hello!
There are 2 Entities in relation with each other: User and 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)
  2. Write an extra class that attaches the user to the context: 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

c#
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; }
}
Was this page helpful?