2014-06-18 39 views
3

我在我的应用程序下面的非常标准的微风API控制端点:微风JS调用查询的SaveChanges之前导致失败

public SaveResult SaveChanges(JObject saveBundle) 
    { 
     return _contextProvider.SaveChanges(saveBundle); 
    } 

我的后台数据库使用的是被配置为身份INT标识。

当从具有有效更改集的客户端调用时,一切正常。

但是,如果在致电我的_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调用之前,是否有其他方法可以执行初始的单独查询,而不会影响某些内容并使查询失败?

回答

5

您需要为执行查询创建第二个上下文。在上面的代码中,EditedUser对象被缓存在上下文中,因为这就是EF所做的。然后,当调用_contextProvider.SaveChanges(saveBundle)时,contextProvider尝试在同一个上下文中创建具有相同类型和相同键的对象。因此错误。

This SO post给出了关于创建第二个上下文的一些提示。

+0

完美的工作!谢谢。这是我最终做的... EFContextProvider _privateContextProvider = new EFContextProvider (); AspNetUser EditedUser = _usersRepo.GetUserById(incomingUserId,_privateContextProvider); –