Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 如何访问新创建的实体上的导航属性_Entity Framework_Code First - Fatal编程技术网

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

Entity framework 如何访问新创建的实体上的导航属性,entity-framework,code-first,Entity Framework,Code First,我首先使用实体框架6代码。我在跟踪导航属性和外键时遇到了一些问题。让我举例说明。在本例中,我正在创建一个对象,并观察在创建FK引用的实体时导航属性发生的情况 实体: 域用户{AccountStatus…,UserAccount,UserAccountId}引用UserAccount 用户帐户{UserAccountId…} 第一种情况-导航属性在创建时为空: 第二种情况-引发InvalidOperationExceptionException 因此,我的问题是,如何使用导航属性UserAccou

我首先使用实体框架6代码。我在跟踪导航属性和外键时遇到了一些问题。让我举例说明。在本例中,我正在创建一个对象,并观察在创建FK引用的实体时导航属性发生的情况

实体: 域用户{AccountStatus…,UserAccount,UserAccountId}引用UserAccount 用户帐户{UserAccountId…}

第一种情况-导航属性在创建时为空: 第二种情况-引发InvalidOperationExceptionException
因此,我的问题是,如何使用导航属性UserAccount?我必须使用UserAccountId从数据库中获取它吗?如果是,我如何将它附加到DomainUser对象上?我觉得这应该是直观的。但事实并非如此。

为什么实体框架会将现有对象重新插入我的数据库?msdn.microsoft.com/en-us/magazine/dn166926。aspx@Colin好的,很酷。因此,第一个案例就是我们要走的路。Null,因为已断开连接。感谢heaps对那篇文章的引用。勒曼知道她的事。
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
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;