【发布时间】:2011-08-05 01:50:24
【问题描述】:
这里首先是消息
对数据库的更改是 提交成功,但报错 更新对象时发生 语境。 ObjectContext 可能在 不一致的状态。内部异常 消息:参照完整性 发生约束冲突: 定义的属性值 引用约束不是 主和之间一致 关系中的依赖对象。
当我尝试在实体框架中插入新数据时会出现问题
我的实体模型
在数据库中,我将关系设置为删除和更新时的级联。这是我对关系所做的唯一更改
我的行动方法:
[HttpPost]
public ActionResult CompleteRegisteration(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = new User
{
DisplayName = model.DisplayName,
FullName = model.Name,
Email = model.Email,
};
user.AuthenticationTokens.Add(new AuthenticationToken
{
ClaimedIdentifier = model.ClaimedIdentifier,
DisplayName = model.Email
});
_userRepository.InsertOrUpdate(user);
_userRepository.Save();
return RedirectToAction("Index", "Home");
}
和用户存储库方法:
private readonly StoryWritingEntities context = new StoryWritingEntities();
public void InsertOrUpdate(User user)
{
context.Users.Attach(user);
context.ObjectStateManager.ChangeObjectState(user,
user.Id == default(int)
? EntityState.Added // if true then this is a new entry
: EntityState.Modified); // if false this is an Existing entry
}
public void Save()
{
context.SaveChanges();
}
问题是context.SaveChanges()users表中插入了一条记录但AuthenticationTokens表中没有插入任何记录
【问题讨论】:
标签: c# .net entity-framework exception-handling