Linq2Sql: Adding an object with childs
-
Lets say my Linq 2 Sql model is like this: Class Movement { Products, ... } Class Product { ... } The problem is that if I create a Movement and populate all of its properties, like:
Movement m = new Movement()
m.SomeProperty = ...
m.SomeProperty = ...
m.Products.Add ( someExistingProduct )
m.Products.Add ( someExistingProduct )
m.Products.Add ( someExistingProduct )movementsRepository.Add ( m )
movementsRepository.Save()I get an error "An attempt has been made to Attach or Add an entity that is not new" The only why i'm getting to achieve the add is like this:
Movement m = new Movement()
m.SomeProperty = ...
m.SomeProperty = ...movementsRepository.Add ( m )
movementsRepository.Save()someExistingProduct = productsRepository.GetById ( ... )
someExistingProduct.Movement = m
productsRepository.Save()someExistingProduct = productsRepository.GetById ( ... )
someExistingProduct.Movement = m
productsRepository.Save()etc..
The problem with this second approach is that if there is a problem with one of the products (which are retrieved by an id specified on a form, etc.) I would need to delete the Movement and etc. I dont find it a very elegant solution. Help please, Thanks