سؤال

I am having trouble understanding at a fundamental level how a one to many relationship should be managed in Entity Framework. In my application I have two tables, DISPLAY_MASTER, and DISPLAY_ITEMS. Their relationship is like so:

DISPLAY_MASTER.DISPLAY_ID 1----->* DISPLAY_ITEMS.DISPLAY_ID

Entity Framework organizes this really intuitively. I am left with a strongly typed DISPLAY_MASTER object that has an ICollection property called DISPLAY_ITEMS.

My confusion lies within how to save the DISPLAY_ITEMS collection back to the database. In my application I am reading in all of the DISPLAY_ITEMS for the particular DISPLAY_MASTER using LINQ into a List<DISPLAY_ITEMS> object called _displayItems. This is then bound to a DataGrid for editing using MVVM. The user can edit existing DISPLAY_ITEMS, delete existing DISPLAY_ITEMS, or add new DISPLAY_ITEMS using the DataGrid. My binding works perfectly and these changes are reflected in _displayItems. Once it comes time to save is where I stop feeling confident in my code. When the user clicks save I am setting the DISPLAY_MASTER's ICollection like so:

_displayMaster.DISPLAY_ITEMS = _displayItems;

Is this the proper way to be working on an Entity Framework collection? Or should I be binding the DataGrid directly to the _displayMaster.DISPLAY_ITEMS object? Or some other method? The reason I am not confident is because if I try to validate the _displayMaster.DISPLAY_ITEMS entity using:

DbEntityValidationResult validationResults = _context.Entry(_displayMaster.DISPLAY_ITEMS).GetValidationResult();

I get an error saying 'List1' is not part of the collection, which obviously doesn't seem right.

Any advice or guidance would be appreciated.

Thanks.

هل كانت مفيدة؟

المحلول

It depends.

  • If you disconnect the entities from their database context when you bind them to the grid (i.e. if you dispose the context after loading the entities and create a new context when it comes to save the changes) then it's not so easy. You will have to load the master including the old items from the database, merge the changes into that collection based on your new edited collection from the grid and then save the changes. An example how to do that is here.

  • If you keep the entities attached to the context you have loaded them into while the user is editing it's much easier if you just directly bind _displayMaster.DISPLAY_ITEMS to the grid because EF is then able to track all the changes you are performing on the collection and update the object graph automatically to the database when you call SaveChanges.

Since you tagged the question with WPF you might have the second option (depending on your application's architecture). In web applications for example the second option doesn't exist at all because all editing happens in a browser which is disconnected of course from the context.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top