EF Code First Update 方法不起作用

EF Code First Update method does not work

我有这个class

public class BankAccount : IEntity
{
    public int Id { get; set; }
    public long AccountNumber { get; set; }
    public string Description { get; set; }
    public bool IsFund { get; set; }

    public virtual Person Owner { get; set; }
    public virtual Branch Branch { get; set; }

    public BankAccount()
    {
        AccountNumber = 0;
        IsFund = false;
        Description = "Empty";
    }
}

和更新方法:

public void Update(DBS.BankAccount entity)
{
    try
    {
        using (var _nahidContext = new NahidContext())
        {
            var bankAccountElement= FindById(entity.Id);
            _nahidContext.Entry(bankAccountElement).State = System.Data.Entity.EntityState.Modified;
            var bankAccount = _nahidContext.Entry(bankAccountElement);
            bankAccount.CurrentValues.SetValues(entity);
            _nahidContext.SaveChanges();
        }
    }
    catch (Exception ex)
    {
        throw new ArgumentException(ex.Message);
    }
}

当我 运行 更新方法并更改 (owner,branch,description) 值时,只是描述确实发生了变化,而 owner,branch 没有任何变化。 我如何更改所有者或分支机构?[谢谢]

我知道有两种方法可以解决这个问题。

添加外键为属性:

public class BankAccount : IEntity
{
    public int Id { get; set; }
    public long AccountNumber { get; set; }
    public string Description { get; set; }
    public bool IsFund { get; set; }

    public int OwnerID { get; set; }
    [ForeignKey("OwnerID")]
    public virtual Person Owner { get; set; }

    public int BranchID { get; set; }
    [ForeignKey("BranchID")]
    public virtual Branch Branch { get; set; }

    public BankAccount()
    {
        AccountNumber = 0;
        IsFund = false;
        Description = "Empty";
    }
}

这应该会更新关系,但不会更新 PersonBranch。这些需要单独更新,就像您更新 BankAccount.

的方式一样

通过分配所有者和分支更新链接。

public void Update(DBS.BankAccount newBankAccount)
{
    try
    {
        using (var _nahidContext = new NahidContext())
        {
            BankAccount oldBankAccount = FindById(entity.Id);

            oldBankAccount.Owner = newBankAccount.Owner;
            oldBankAccount.Branch = newBankAccount.Branch;
            oldBankAccount.CurrentValues.SetValues(newBankAccount);

            _nahidContext.SaveChanges();
        }
    }
    catch (Exception ex)
    {
        throw new ArgumentException(ex.Message);
    }
}

然而,这将创建一个新的 Person 和一个新的 Branch