How to use DBContext.Add / Attach (using EF CodeFirst 4.1) with nested objects

Problem: when adding an object to "dbcontext", all nested order objects are "read" into the database, although nested objects are static data and only the shoudl link is added to the database.

Example: The database contains 0 orders and 3 items.

I add one order with two items.

Now the database contains 1 order and 5 items. Two items in order were β€œread” in the database, although the items had the correct primary keys before db.SaveChanges ().

I understand that I can attach existing elements to dbcontext before saving changes, but is this really the only way? Can EF find out that an element already exists when the primary key matches an existing element?

Does anyone know if this is different in the new version of EF CodeFirst?

+4
source share
1 answer

No, EF cannot understand whether entities exist, one or a new one - both Add and Attach commands are graph-oriented operations. You call them on one object in the graph, and they cross all the relations (and their relations, etc.) and perform an operation for them.

You must correctly determine the state of each object in the graph using:

dbContext.Orders.Add(newOrder); foreach(var item in newOrder.Items) { dbContext.Entry(item).State = EntityState.Unchanged; } dbContext.SaveChanges(); 

You can use the inverse operation by calling Attach(newOrder) and set the order to Added . The main difference will come with independent associations (for example, many-to-many relationships). The first approach will correctly add a new relationship between the order and each element, while the second will not, unless you manually set each relation to the Added state (and changing the state for relations is more complicated).

+5
source

Source: https://habr.com/ru/post/1433381/


All Articles