Search code examples
c#asp.net-mvcpetapoco

PetaPoco/NPoco - saving object with (child) collection property


I'm using NPoco with SQL Server, and have a parent object which contains a collection property. This all loads fine using FetchOneToMany.

I want to save the parent object and the child collection. Passing the parent to Update() or Insert() does not change the DB for the child collection. Do I have to manually iterate through the child collection and delete/insert/update each item as appropriate?

I don't mind doing that manually; I have the code within a transaction but it deletes all objects in the collection, and re-adds the new ones, which just seems a bit dodgy.

So, I really need to ask in case there is a better way that I might be missing.

Thank you.


Solution

  • Yes, you have to do it manually.

    To avoid deleting and then inserting you have to keep the items ID (I always have an autoincrement primary key) in the UI and the post them to backend so you can update, insert or delete.

    I use ASP.net MVC, and there I keep a list of all items with a hidden field with the ID. In my UI, the only way to delete an item, it's to clear all field, but the hidden ID it's still in place, so later I can delete the item in the DB. For insert/update it's easy because you only have to check if the ID it's not empty.