如何在新创建的实体上访问导航属性

时间:2013-11-15 03:07:16

标签: entity-framework code-first

我首先使用实体​​框架6代码。我在跟踪导航属性和外键的情况时遇到了一些麻烦。让我详细说明一个例子。在这个例子中,我创建了一个对象,并在创建FK引用的实体时观察导航属性的情况。

实体:

DomainUser {AccountStatus ...,UserAccount,UserAccountId} 引用UserAccount

UserAccount {UserAccountId ...}

第一种情况 - 导航属性在创建时为空:

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

第二种情况 - 抛出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从数据库中获取它?

< p>如果是这样,我如何将它附加到DomainUser对象?

我觉得这应该是直观的。但事实并非如此。

0 个答案:

没有答案