如何使用外键 access/modify 数据库中的实体?

How do I access/modify entities in a Database using Foreign Keys?

我正在尝试访问数据库中的实体以确保在我的数据库中执行更改时的数据完整性。

我正在测试更改外部 Key/Navigational 属性以指向关联 Table 中不同行的不同方法。

我的Childclass是这样的,

public string Name { get; set; }
public decimal Balance { get; set; }    

public int AccountTypeId { get; set; }
public virtual AccountType AccountType { get; set; }    

和对应的Parent,

public string Name { get; set; }

public virtual ICollection<Account> Accounts = new ICollection<Account>()

我正在使用工作单元和存储库模式来访问数据,因此在我的测试中 class 我执行以下操作;

(uow = new UnitOfWork)

AccountType accountType1 = new AccountType() { Name = "Bank" };
AccountType accountType2 = new AccountType() { Name = "Loan" };

uow.AccountTypes.Add(accountType1);
uow.AccountTypes.Add(accountType2);
uow.Commit();

Account account1 = new Account() { Name = "RBS", Balance = 20, AccountTypeId = 1 };

uow.Accounts.Add(account1);
uow.Commit();

然而,在尝试访问 account1AccountType 属性 时失败了,我尝试将 AccountType 设置为 accountType1 的引用,但是,当涉及到将 AccountType 从一个更改为另一个时,它需要我从数据库加载新的 accountType,然后将其分配给 Account,每次我做这个改变,而不是简单的改变Foreign key。有没有办法通过 Foreign Key 更改关联并仍然允许 lazy loading?或者我是否需要使用 parent 实体 table 上的 Foreign Key 提供自己的查询?

谢谢!

编辑

如果我创建实体并将它们全部保存在一个上下文中,然后尝试访问导航属性,这是可行的,但是如果我处理上下文,然后在新的上下文中执行查询,它将无法加载信息。

您需要将父项的引用分配给每个子项,例如:

 (uow = new UnitOfWork)
    AccountType accountType1 = new AccountType() { Name = "Bank" };
    uow.AccountTypes.Add(accountType1);

Account account1 = new Account() { 
Name = "RBS", 
Balance = 20, 
AccountTypeId = 1 
AccountType = accountType1
};

uow.Accounts.Add(account1);
uow.Commit();

而且你不需要为一个事务在很多地方提交