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
4 Replies
Hello @Core ,
As you mentioned the 2nd option seemed better to me, however I can give you a new option also.
You can add a new property to the Domain,
public string UserId {get;set;}
While you are adding a related entity you can equal yourDomainObj.UserId = userId
This approach works well If you also don't update your user object as well beside you are not doing it.
Thank you for answering! Initially I used to have extra fields
public string UserId {get;set;}
, but then it was a bit confusing when I needed to access the UserId.
I could have accessed it with DomainObj.User.UserId
and DomainObj.UserId
And when an Entity gets bigger it is easy to access a value that is null
I will go with option 2 thenNaming differs so much, I would prefer to use
public class User
{
public string Id { get; set; }
}
rather than UserId, because whenever you are accessing an user object you are going to use it myUserObj.Id so as you said If UserId naming is used there it may be confusing.
Or you can use another naming like DomainUserId, and either in fluent api or with an attribute you can say it's a foreign key. It is completely up to you.
I am happy if I could help you
Yes, there are many options available, I just could not decide. Thanks again