UpdateOrInsert Into in EF6

126 views
Skip to first unread message

Marcelo Krol

unread,
Apr 13, 2021, 4:20:50 PM4/13/21
to firebird-n...@googlegroups.com
In EF6, where there is a relationship between two tables (People and Addresses for example). If the People class is popular and also inform the Address data, and send the EF to do the insertion:
_dbSet.Add (entity);
_context.SaveChanges ();
Both Person and Address data are persisted in the database.
But, if you use the same classes above, and making the change in the Name property of the Person class, but now using the commands to do the update:
_dbSet.Attach (entity);
_context.Entry (entity) .State = EntityState.Modified;
Returns the error:
System.InvalidOperationException: 'Attaching an entity of type' People 'failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate. '

If you perform the same procedures above, but leaving the Address property as null, the error does not happen, that is, to make the change I have to send class to class, am I right?
Question 1: In this case, the EF to insert a safe save, but if it is to change, do I have to do the class by class?
Question 2: Do you have any method where you can pass the Person class with the provided address data and EF make use of the UpdateOrInsert into feature of firebird, using both Save and Change?

Jiří Činčura

unread,
Apr 14, 2021, 3:34:19 AM4/14/21
to 'Mr. John' via firebird-net-provider
> Question 1: In this case, the EF to insert a safe save, but if it is to
> change, do I have to do the class by class?

No. You just need to make sure that you graph is consistent. That means, when you're attaching manually something, the change tracker's current data should not collide with the attached graph.

> Question 2: Do you have any method where you can pass the Person class
> with the provided address data and EF make use of the UpdateOrInsert
> into feature of firebird, using both Save and Change?

No. The entity is either in Added or Modified state and according to this state the EF will do insert or update.

--
Mgr. Jiří Činčura
https://www.tabsoverspaces.com/

Reply all
Reply to author
Forward
0 new messages