EF Code First Update方法不起作用

时间:2016-02-04 16:06:29

标签: c# entity-framework code-first

我有这个课程

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

当我运行更新方法并更改(所有者,分支,描述)值时,描述确实会发生变化,所有者,分支机构也无法进行任何更改。 我怎样才能改变所有者或分支?[谢谢]

1 个答案:

答案 0 :(得分:0)

我知道有两种解决方法。

将外键添加为属性:

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