originalentity cannot be specified for an insert operation - entity-framework

I'm currently working with Silverlight and the RIA services Entity Framework. Today I have encountered an error message saying "invalid changeset: originalentity cannot be specified for an insert operation". I Googled with no result, so my question is: has anyone ever encountered the same problem?
Here are the steps to reproduce the error:
create a new entity and add it to its entity set
submit changes
remove the entity
submit changes
add again the entity to the entity set
submit changes -> the error shows up here
Since the status of the entity is "new", my hypothesis is that the framework is trying to perform an insert operation, but the data that is passed to the server side still has some information on the entity as it was inserted before (the "originalentity", which is probably meant to be used in update operations), so the insert operation fails. What do you think?

Related

MDS Error when creating a Entity Sync to an New Target Entity

When I try to create an Entity Sync in Master Data Services 2016, I receive the following error (fyi I chose to create a new target entity).
Not sure why this is occurring. Ideas?
It turns out that the Code attribute on the Source entity is the problem as indicated in the error message. It needs to have its display width match its length or you will get this error. See snip below

Entity Framework Core 2.0 deleting record instead of updating it

I think this could be a bug but thought I might be missing something that could explain the behavior. Any help would be appreciated.
### Technical details
EF Core version: Microsoft.EntityFrameworkCore (2.0.1)
Database Provider: Microsoft.EntityFrameworkCore.SqlServer (2.0.1)
Database: SQL Server 2008
Operating system: Windows 10
IDE: Visual Studio 2017 Community Edition (15.4.4)
I've got a situation in a C# console application where I call Update on my DbContext (location is a LocationParty):
_context.Update(location);
The only change in the record is to the EndDate Field. Just prior to the call to SaveChangesAsync() examining _context.ChangeTracker shows that the entity is marked as modifed. All of the 43 other entities being tracked are marked as Unchanged.
Watch Window Image showing Modified Entity Status
The return value from SaveChangesAsync() is 1 indicating that one entity had changes. The SQL executed is a delete statement rather than an update which results in the record being removed rather than updated:
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (28ms) [Parameters=[#p0='8431'], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
DELETE FROM [LocationParties]
WHERE [ID] = #p0;
SELECT ##ROWCOUNT;
The code invoking the database changes (using the Repository Pattern) is shared between this console application and an MVC application. When the same update location code is called from the MVC application the record is properly updated. Note that when run by the MVC controller there is only the one entity being tracked when SaveChangesAsync() is called and that entity is also marked as Modified. In the console application there are 44 entities being tracked with only the entity of interest marked as modified. I looked to see if there was perhaps another instance of the entity being tracked in a Delete status but there is no such entity.
Update:
I may have figured out what is going on but don't know if the behavior is to be expected.
The LocationParty entity is in a one to many relationship with the Party entity (one Party has multiple locations). If I remember right I was getting some EF errors regarding tracking objects that were already being tracked (in my MVC app) when I first got started with EF. The Location Party has a Foreign Key to the Party entity (PartyID) and a navigation property to the Party entity. In the update method I had see that Party navigation property to null prior to the update to eliminate this problem. The foreign key was still set to point to the Party.
I assume that EF is keying off of the navigation property being null to infer that the Party was deleted and therefore the associated location should be deleted. The Party was not deleted by the update. I can't explain why it worked for the MVC app but not the Console app.
I commented out the code the set the Party navigation property to null and the location updated properly in both the console and MVC app.
My code was kind of weird but I assumed that setting the Foreign Key to point to a valid entity would be all that was required.

Breeze JS : Entity Errors preventing patch-up on the client

I my client application I am calling entityManager.saveChanges to send all currently changed entities from the client up to the server. Then in the BeforeSaveEntity event on the server I am performing some server side validation on each entity to see if it should be excluded from the save map. So for example, my entity may have a value for description that is too long. So I return false from BeforeSaveEntity, and generate a new EntityError which will then be added to the saveResult.EntityErrors collection. All of the valid records that haven't been excluded from the save map then save off successfully, and my saveResult is returned to the client. But because of this single entity error, the auto-patchup of the entities returned does not occur back on the client. I looked at the source and basically there seems to be a check that says if there is anything in the saveResult.EntityErrors collection, don't bother with the patch-up. But There was only 1 entity that purposefully wasn't saved, so I still want to be able to patch up the others. Is this behavior by design? I want to be able to exclude certain entities from the save (which I can do using the BeforeSaveEntity event), but there doesn't seem to be any way of then getting the entity errors back to the client using the inbuilt mechanism, without the full patch-up being abandoned.
Saves in breeze are transactional if at all possible ( some backend providers, like MongoDb are not because they don't support it.). This means that if any failures are experienced with any entities within a save bundle the entire save is reverted and an error is returned to the client. This is by design.

Entity Framework 5 - "Conflicting Changes Detected"

In our EF 5 application, when we get a SQL Server deadlock error on an insert or update, we immediately try the operation again. However, when we attempt to do so, we're getting the following error:
"Conflicting changes detected. This may happen when trying to insert multiple entities with the same key."
This error is not coming from SQL Server. This is an EF 5 error. And we are not attempting to insert multiple entities with the same key. IOW, we're not attempting to insert a duplicate row. However, I suspect this error means something else. But I'm not entirely certain I know what the issue is. If I had to guess, I would say that on the first attempt, EF sees where trying to insert an entity. It fails because of a deadlock. When we immediately try again, EF thinks we're trying to do the very same operation again, with the same key, and doesn't like it. Not sure how to get around this.
It sounds like you might be trying to execute your queries against the same instance of the DbContext. In which case, your changes are already pending from the last try.
Since there is no “undo pending changes” on the context, you must dispose and recreate the context in between “retries”.

Removing an entity, but using the same primary key to add a similar entity after the removal

Im trying to remove an entity which has a unique PK like : 80253
I remove this entity by doing the follow lines of code:
myEntityType1 = getEntityManager().find(MyEntityType1.class, 80253);
getEntityManager().remove(myEntityType1);
getEntityManager().flush();
These bits of code actually deletes the rows from my database and all its cascading objects properly, and Im very happy about this. Now the problem occurs when I now need to create a similar entity that uses the same primary key (which should now be gone right?).
MyEntityType2 myEntityType2 = new MyEntityType2 ();
myEntityType2.copyData(myEntityType1); //access the data from the other object
//and retrieves the id 80253. myEntityType2 now has 80253 as ID.
getEntitymanager().persist(myEntityType2);
Now this is where I get a unique constraint SQL error. Im trying to insert a ID which already exists and the changes are automatically rolled back (the old entity is no longer deleted). This happens after I see in my logger that toplink has deleted the records of the old entity.
Does anyone know how this happens, and why its not working? For the record Ive tried merging, closing, clearing of the entityManager, but nothing seems to work.
It seems to me that JPA might do some bad caching or something. I hope someone has a good answer for me! =)
Update: Theres no longer an issue with unique ID constraints, but I create a new subclass with the same primary key which has been deleted I get the following exception:
Exception Description: Trying to invoke [setApprovedWhen] on the object [null]. The
number of actual and formal parameters differs, or an unwrapping conversion has failed.
Internal Exception: java.lang.IllegalArgumentException: object is not an instance of
declaring class
It seems to me that it wont let me change the object into a different subclass?
EDIT:
Try with explicitly start and commit transaction.
Deleting an entity is as simple as
calling EntityManager method
remove(Object entity) as the following
example shows. The entity you delete
must be managed: that is, it must have
been previously read in the current
persistence context.
entityManager.getTransaction().begin();
myEntityType1 = getEntityManager().find(MyEntityType1.class, 80253);
getEntityManager().remove(myEntityType1);
entityManager.getTransaction().commit();
When the transaction is completed, or
you call EntityManager method flush(),
the entity will be deleted.
In a container managed persistence
context the transaction boundaries
will be controlled by the container.