shredding
shredding

Reputation: 131

Entity framework DBcontext add child row

As I understand, to add a child row, you can either do

parent.Children.Add(child);

or

child.Parents= parent

Then you can do myContext.SaveChanges();

Somehow the second solution doesn't do the insert work at all. Here's my code:

        CountMaster countMaster = (from b in pMDataContext.CountMasters
                                   where b.ReportDate == reportDate && b.Department == dept
                                   select b).SingleOrDefault();



        CountDetail countDetail = new CountDetail { CategoryId = 1, StatusId = 1 };

        //countMaster.CountDetails.Add(countDetail);

        countDetail.CountMaster = countMaster;

        pMDataContext.SaveChanges();

Upvotes: 1

Views: 1372

Answers (1)

user1914530
user1914530

Reputation:

When adding an entity to the collection navigation property or setting it to a reference navigation property of an already tracked entity then EF will add that entity to the context in the EntityState.Added state. This is due to the ObjectStateManager detecting changes made to the tracked entity.

If you are working the other way around, that is, starting with an untracked entity and setting/adding tracked entities to reference/collection properties, then the ObjectStateManager has no way of detecting changes you make to that untracked entity. Therefore you need to explicitly add the entity to the context before SaveChanges().

countDetail.CountMaster = countMaster;
context.CountDetails.Add(countDetail);
pMDataContext.SaveChanges();

Upvotes: 4

Related Questions