我将所有DBContext调用都移到了存储库中。
public class PayAllowanceRepository
{
private static DBEntities _dbContext = new DBEntities();
public static void AddAllowance(Allowance payAllowance)
{
_dbContext.Allowances.Add(payAllowance);
_dbContext.SaveChanges();
}
public static void AddAllowanceAccumulators(List<Allowance> allowanceList)
{
_dbContext = new DBEntities();
_dbContext.Allowances.AddRange(allowanceList);
allowanceList.ForEach(p => _dbContext.Entry(p).State = System.Data.Entity.EntityState.Modified);
_dbContext.SaveChanges();
}
// Here
public static void AddAllowanceAccumulatorsHours(List<Allowance> allowanceListHours)
{
_dbContext = new DBEntities();
_dbContext.Allowances.AddRange(allowanceListHours);
allowanceListHours.ForEach(x => _dbContext.Entry(x).State = System.Data.Entity.EntityState.Modified);
_dbContext.SaveChanges();
}
public static void UpdateAllowance(Allowance payAllowance)
{
_dbContext=new DBEntities();
_dbContext.Entry(payAllowance).State = System.Data.Entity.EntityState.Modified;
_dbContext.SaveChanges();
}
public static void DeleteAllowance(Guid id)
{
var allowance = _dbContext.Allowances.FirstOrDefault(x => x.Id == id);
_dbContext.Allowances.Remove(allowance);
_dbContext.SaveChanges();
}
public static void UpdateAllowanceRate(Allowance allowanceRate)
{
//dbContext.Allowances.Add(allowanceRate);
_dbContext.Entry(allowanceRate).State = System.Data.Entity.EntityState.Modified;
_dbContext.SaveChanges();
}
public static List<Allowance> GetAllowances(Guid payrollCompanyId)
{
var allowance = new List<Allowance>(_dbContext.Allowances.AsNoTracking().Where(x => x.PayrollCompanyId == payrollCompanyId));
return allowance;
}
}
答案 0 :(得分:0)
如果我不重新初始化dbContext,例如_dbContext = new DBEntities(); 我收到错误消息: 附加类型的实体失败,因为相同类型的另一个实体已具有相同的主键值。如果图中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。这可能是因为某些实体是新的并且尚未收到数据库生成的键值。在这种情况下,使用“添加”方法或“已添加”实体状态来跟踪图表,然后根据需要将非新实体的状态设置为“未更改”或“已修改”。
现在几乎在我的所有存储库中都会出现此问题。