代码之家  ›  专栏  ›  技术社区  ›  Tristan Trainer Ferguson Osas

如何使用外键访问/修改数据库中的实体?

  •  1
  • Tristan Trainer Ferguson Osas  · 技术社区  · 6 年前

    我试图从数据库访问实体,以确保在数据库中执行更改时数据完整性。

    我正在测试更改外键/导航属性的不同方法,以指向关联表中的不同行。

    我的孩子班看起来像这样,

    public string Name { get; set; }
    public decimal Balance { get; set; }    
    
    public int AccountTypeId { get; set; }
    public virtual AccountType AccountType { get; set; }    
    

    以及相应的父母,

    public string Name { get; set; }
    
    public virtual ICollection<Account> Accounts = new ICollection<Account>()
    

    我使用工作单元和存储库模式来访问数据,所以在我的测试类中,我做了以下工作:

    (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();
    

    但是,在尝试访问 AccountType 的属性 account1 这失败了,我尝试设置 账户类型 参考 accountType1 但是,当涉及到改变 账户类型 从一个到另一个,它要求我加载新的 accountType 从数据库中,然后将其分配给 Account 每次我做这个改变,而不是简单的改变 Foreign key . 是否没有方法通过 Foreign Key 仍然允许 lazy loading ?或者我需要提供我自己的查询,使用 外键 在父实体表上?

    谢谢!

    编辑

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

    1 回复  |  直到 6 年前
        1
  •  0
  •   sharmav1    6 年前

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

     (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();
    

    另外,您不需要在多个地方提交一个事务。