我想了解为什么“ ObjectContext可能处于不一致状态”。发生异常。 我知道有多个与类似问题相关的主题,但是似乎没有一个主题可以回答我的问题。 (最接近我的问题是:The changes to the database were committed successfully...The ObjectContext might be in an inconsistent state)
我有包含表的Database First模型:
Training (PK Id)
User (PK Id)
UserTraining(PK (UserId, TrainingId), FK(UserId), FK(TrainingId))
Documentation(PK Id, FK TrainingId)
UserDocumentation (PK (UserId, TrainingId, DocumentationId),
FK(UserId, TrainingId), FK(DocumentationId))
以上所有表均已正确映射为代码(存在所有键等)。
我正在做的是-使用文档创建培训,然后使用UserDocumentation创建UserTraining,如下所示:
var type = this.trainingRepository.GetTrainingType(command.Training.TypeId);
var training = new Training(
type,
command.Training.Name,
command.Training.Documentation,
...);
if (type.Equals(TrainingType.Mandatory))
{
var users = this.userRepository.GetAllUsers();
foreach(var user in users)
{
user.AssignTraining(training);//under the hood is created new instance of UserTraining with relation to training and UserDocumentation related to UserTraining and Documentation from training
}
}
trainingRepository.Add(training);
trainingRepository.SaveChanges();
有2个存储库,但是每个存储库都使用相同的DBContext实例(注册为PerRequest)。
现在,如果我将添加和保存更改移到 if(type.Equals(TrainingType.Mandatory))上方,并在方法末尾添加一动SaveChanges,则一切顺利通过。
不幸的是,在上述情况下,它引发标题中提到的异常。 现在的问题-为什么在中间添加然后更新工作,而我的解决方案却没有?可能与不良的数据库架构或EF限制有关吗?
AssignTraining方法:
public void AssignTraining(Training training)
{
this.State.UserTrainings.Add(new UserTraining(training));
}
UserTraining构造函数:
public UserTraining(Training training) : base(new
DataAccess.Database.UserTraining())
{
this.State.Training = training;
if(training.Documentation != null)
{
this.State.UserDocumentations.Add(new UserDocumentation(training.Documentation));
}
}