我有两个类,这里是相关的位:
public class Endorsement
{
public Guid? ContractId { get; set; }
public virtual Contract Contract { get; set; }
}
public class Contract
{
public virtual ICollection<Endorsement> Sales { get; set; }
}
Endorsement
类没有相应的配置,但Contract
类确实如此:
public class ContractConfiguration : EntityTypeConfiguration<Contract>
{
public ContractConfiguration()
{
HasMany(a => a.Sales).WithRequired(a => a.Contract).HasForeignKey(a => a.ContractId);
}
}
我正在尝试将Contract
上的Endorsement
更改为另一个Contract
:
var endorsement = Context.Set<Endorsement>().Find(endorsementId);
var newContract = Context.Set<Contract>().Find(newContractId);
endorsement.Contract = newContract;
/* Instead of the line above, I have also tried endorsement.ContractId = newContract.Id;
I have also tried newContract.Sales.Add(endorsement); and then setting the state of
the newContract entry to modified and saving, all with the same results.
*/
var entry = Context.Entry(endorsement);
entry.State = EntityState.Modified;
Context.SaveChanges();
Context.SaveChanges();
抛出以下异常:
已成功提交对数据库的更改,但更新对象上下文时发生错误。 ObjectContext可能处于不一致状态。内部异常消息:发生了引用完整性约束违规:关系一端的“Contract.Id”的属性值与另一端的“Endorsement.ContractId”的属性值不匹配。 / p>
知道造成这种情况的原因是什么?