我的应用程序中有以下非常标准的 Breeze API Controller 端点:
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
我的后端数据库使用配置为身份的 int ID。
当从具有有效更改集的客户端调用时,一切都很好。
但是,如果,之前调用我的
_contextProvider.SaveChanges(saveBundle) function
,我进行任何形式的查询。例如: public SaveResult SaveChanges(JObject saveBundle)
{
int incomingUserId = Convert.ToInt32(saveBundle["entities"][0]["Id"]);
AspNetUser EditedUser = (from u in Context.AspNetUsers where u.Id == incomingUserId select u).FirstOrDefault();
// ......
// do something with the EditedUser (like validations of any sort)
// ......
return _contextProvider.SaveChanges(saveBundle);
}
保存失败并出现错误:
Saving or accepting changes failed because more than one entity of type 'xxxx.App_Data.AspNetUser' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.
鉴于我在做什么,这是预期的行为吗?有没有其他方法可以在 SaveChanges 调用之前进行初始的单独查询,而不会打扰某些事情并使查询失败?
最佳答案
您需要创建第二个上下文来执行查询。在上面的代码中,EditedUser
对象被缓存在上下文中,因为这就是 EF 所做的。然后,当 _contextProvider.SaveChanges(saveBundle)
被调用时,contextProvider 会尝试在同一个 Context 中创建一个具有相同类型和相同键的对象。因此错误。
This SO post给出了有关创建第二个上下文的一些提示。
关于sql - Breeze JS Query 在调用 SaveChanges 之前导致失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24292689/