实体框架核心添加并更新相关对象

时间:2016-12-21 02:41:12

标签: c# entity-framework

我是Entity Framework的新手,我正在尝试了解如何执行相关实体的更新。我使用以下代码更新相关实体。

if (ModelState.IsValid)
{
    using (var dbContextTransaction = _context.Database.BeginTransaction())
    {
        cp = new Payment
        {
                CustomerId = vm.SelectedCustomerID,
                PaymentAmount = Convert.ToInt32(vm.PaymentAmount),
                PaymentDate = Convert.ToDateTime(vm.PaymentDate),
                PaymentMethod = await _context.PaymentMethod.SingleAsync(pm => pm.PaymentMethodName == vm.PaymentMethod),
                TransactionType = await _context.TransactionType.SingleAsync(tt => tt.TransactionTypeName == "PaymentReceived")
        };

        Customer c = await _context.Customer.SingleOrDefaultAsync(m => m.CustomerId == vm.SelectedCustomerID);

        int updatedOutstandingAmount = c.CurrentAmountOutstanding - cp.PaymentAmount;
        c.CurrentAmountOutstanding = updatedOutstandingAmount;

        _context.Update(c);
        _context.Add(cp);

    }
}

付款类中有一个相关的客户对象,但由于我正在插入新的付款记录,同时我还需要更新即客户属性的出售金额,我想知道如何附加客户实体到此付款并在一次交易中运行插入和更新。或者我在下面做的方式是正确的方法吗?

0 个答案:

没有答案