When I want to add a new related objects I can use this method to do so:
- pull the parent object from the database,
- find the property (it's an
EntitySet
I believe) holding the one-to-many relation to the other model, - insert a new child object there
- and finally save the parent class
Example:
var post = db.Post.Single(x => x.Id == 1);
post.Tag.Add(new Tag(){ name="Brand new!" };
db.SubmitChanges();
This may look like some extra hassle in compare to simply adding the child object directly to the DB, but when one has to use generic services (meaning access to DBContext is being obscured inside of a controller) to handle DB operations it can be actually convenient (well sometimes).
Now, is it possible to delete a related object in a similar fashion?
I remember experimenting with the idea before, but never succeeding (I think the exceptions were mentioning the fact that object being attached to the DB as a reason for failures).
I know I can simply write:
var model = db.Tag.Single(x => x.PostId == 1 && name == "Brand new!");
db.Tag.DeleteOnSubmit(model);
db.SubmitChanges();
and be done with it. In the context of my project such code would be placed in an custom service inheriting from the generic one. The point is, I just want to know if a related object can be deleted while updating the parent object or not. If it's possible, that might help me produce some prototype code faster, if not I just handle it the standard way.