Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breeze JS Query before calling SaveChanges causes failure

Tags:

sql

breeze

I have the following very standard Breeze API Controller endpoint in my app:

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

My backend database uses int IDs that are configured as identities.

When called from a client with a valid change set, all is well.

However, if, prior to the call to my _contextProvider.SaveChanges(saveBundle) function, I make a query of any sort. For example:

    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);
    }

the save fails with error:

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.

Given what I am doing, is this expected behavior? Is there any other way to do an initial, separate query just prior to the SaveChanges call without upsetting something and making the query fail?

like image 264
Dennis Guthrie Avatar asked Mar 20 '23 07:03

Dennis Guthrie


1 Answers

You'll need to create a second Context for performing the query. In the code you have above, the EditedUser object is being cached in the Context, because that's what EF does. Then, when _contextProvider.SaveChanges(saveBundle) is called, the contextProvider tries to create an object with the same type and same key in the same Context. Hence the error.

This SO post gives some hints about creating the second Context.

like image 193
Steve Schmitt Avatar answered Mar 22 '23 23:03

Steve Schmitt