最初にエンティティ フレームワーク 6 コードを使用しています。ナビゲーション プロパティと外部キーに対して何が起こっているのかを追跡するのに少し問題があります。例を挙げて詳しく説明しましょう。この例では、オブジェクトを作成し、FK が参照するエンティティを作成するときにナビゲーション プロパティに関して何が起こるかを観察しています。
エンティティ:
DomainUser {AccountStatus … , UserAccount, UserAccountId} は UserAccount を参照します
UserAccount { UserAccountId ... }
最初のケース - 作成時にナビゲーション プロパティが null である:
var newAccount = userAccountService.CreateAccount(userName, password, email);
var domainUser = new DomainUser
{
AccountStatus = active,
UserAccountId = newAccount.ID
};
domainUserRepository.Add(domainUser); // save changes is called on the context in this method.
return domainUser; // at this point, the UserAccount property of domainUser is null
2 番目のケース - InvalidOperationExceptionException がスローされる
var newAccount = userAccountService.CreateAccount(userName, password, email);
var domainUser = new DomainUser
{
AccountStatus = active,
UserAccount = newAccount
};
domainUserRepository.Add(domainUser); // "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."
return domainUser;
私の質問は、ナビゲーション プロパティ UserAccount をどのように使用できますか?
データベースから取得するために UserAccountId を使用する必要がありますか?
もしそうなら、どうすればそれを DomainUser オブジェクトにアタッチできますか?
これは直感的なものであるべきだと思います。しかし、そうではありません。