简体   繁体   English

EF代码优先更新方法不起作用

[英]EF Code First Update method does not work

i have this 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";
    }
}

and update method: 和更新方法:

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

when i run update method and change (owner,branch,description) value just description does change and owner,branch haven't any change. 当我运行更新方法并更改(所有者,分支,说明)值时,说明确实发生了更改,所有者,分支没有任何更改。 how can i change owner or branch?[Thanks] 我该如何更改所有者或分支机构?[谢谢]

There are two ways that I know of to solve this. 我知道有两种解决方法。

Add foreign key as property: 添加外键作为属性:

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

This should update the relation, but not the Person or Branch . 这将更新关系,但不会更新PersonBranch Those need to be updated separately, the same way you're updating BankAccount . 那些需要分别更新,就像更新BankAccount

Update the linked by assigning Owner and Branch. 通过分配所有者和分支来更新链接。

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

This will however create a new Person and a new Branch . 但是,这将创建一个新的Person和一个新的Branch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM