实体框架-保存前阅读更新

时间:2020-09-02 19:56:31

标签: c# entity-framework

在EF 6中,当我对实体中的记录进行更新时,在通过调用_context.SaveChanges()保存更改之前,我应该能够在其他函数中访问此更新的记录以及其他记录,以能够验证更改。

public bool UpdateToFlase(int id, int accountNumber)
{
    var charge = _context.CHARGES.FirstOrDefault(x=>x.Id == id).Active = False;
    if(!IsValid(accountNumber))
        return false;
    _context.SaveChanges();
    return true;
}

public bool IsValid(int accountNumber)
{
    return _context.CHARGES.Where(x=>x.AccountNumber == accountNumber && x.Active).Sum(x=>x.Charge) >=0;
    
    //I noticed that the above update that i made is only in _context.CHARGES.Local and by accessing _context.CHARGES, 
    //i'm unable to access the updates. I was hoping to find a way to access records along with the updated one.
}


Given:
    Id  AccountNumber   Charge  Active
    1   10001           100     True
    2   10001           -100    True
    
When
    UpdateToFalse(1, 10001)
Then
    Actual:
        return TRUE
    Expected:
        return FALSE

Expectation 
    In IsValid function, (-100 >= 0) should return false

4 个答案:

答案 0 :(得分:1)

我相信您正在尝试访问一个在上下文中加载到dbset集合中的实体,除非您调用该实体,否则不会“更新”

 SaveChanges()

我相信这是因为EF从首次将它们加载到集合中以来就一直在跟踪它们。我认为只有当您调用SaveChanges()进行“更新”时,它才会被“更新”

也许您可以尝试将修改后的实体传递给isValid函数,并可能修改isValid函数,以便它可以检查您要保存的值?

也许本文可以帮助您防止不必要的实体保存在数据库中:

https://dotnettutorials.net/lesson/entity-state-in-entity-framework/

答案 1 :(得分:0)

我像这样修改并删除了实体

            var modifiedEntities = _context.ChangeTracker.Entries()
                .Where(p => p.State == EntityState.Modified || p.State == EntityState.Deleted)
                .ToList();

            foreach (var change in modifiedEntities)
            {
                Validate(change);
            }

答案 2 :(得分:0)

有效的方法:

public bool UpdateToFlase(int id, int accountNumber)
{
    var charge = _context.CHARGES.FirstOrDefault(x=>x.Id == id).Active = False;
    if(!IsValid(_context.CHARGES.Where(x=>x.AccountNumber == accountNumber).ToList()))
        return false;
    _context.SaveChanges();
    return true;
}

public bool IsValid(List<CHARGES> charges)
{
    return charges.Where(x=>/*What ever the criteria is */ x.Active).Sum(x=>x.Charge) >=0;
    
    //This way, we are referring to same scope as the above function 
}

答案 3 :(得分:-1)

这不会考虑并发请求,但是假设这不是问题,您可以执行以下操作:

public bool IsValid(int id, int accountNumber)
{
    return _context.CHARGES.Where(x=>x.AccountNumber == accountNumber && x.Active && x.Id != id).Sum(x=>x.Charge) >=0;
}

您要执行的操作是获得除您要使其不活动的费用以外的所有活动费用的总和,因此在上面明确排除了费用。

您尝试执行此操作的方法将无法工作,因为直到您调用SaveChanges()才会更新数据库。