在提交之前从上下文中获取数据

时间:2015-10-16 11:57:15

标签: c# sql entity-framework sql-server-2008

customers customer = GetCustomer();
customer.UserId = userId;
customer.NeedToPayTax = true;
customer.IsApproved = false;
_customerRepository.Create(customer);

稍后在我们提交之前,我尝试搜索这个新的customer

public int GetUncofirmedCount()
{
    var query = from p in _context.Set<customers>()
                where p.IsApproved == false
                select p;

    return query.Count();
}

但尺寸始终为0。如果我提交,那么我可以看到正确的结果。为什么?如何从上下文中获取数据,即使尚未提交?

1 个答案:

答案 0 :(得分:1)

未经测试的代码:

    _customerRepository.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
.Where(o => o.GetType() == typeof(Customer) && o => !o.IsApproved)
.Count();

或者,对于较新版本的EF,请查看Local;

_customerRepository.Customers.Local
    .Where(o => o.GetType() == typeof(Customer) && o => !o.IsApproved)
    .Count();