views:

91

answers:

2

How do you handle the case when an entity needs to create, in one of its methods, other entities? My problem is that since each individual entity doesn't have access ObjectContext object, that one with the AddToBlahs() methods, it cannot do it.

For example, having a Site model that has a UpdateLinks() method that is supposed to create Link objects belonging to that Site. The UpdateLinks() method doesn't have an ObjectContext. What do you do? Do you pass one to it, like this:

public void UpdateLinks(ProjectEntities db) {
    foreach (var link in FetchLinks()) {
        db.AddToLinks(link);
    }
}

or do you use another pattern?

+2  A: 

You don't need the context for this.

Since Site.UpdateLinks is creating Link objects belonging to the instance, the instance will have associations with the new Site. Adding a Link to Site.Links automatically makes the new Link part of the same context (if any) as the Site. Likewise, when you save the Site the Link will be saved with it.

Craig Stuntz
I've tried doing Links.Add(link) where Links is the LinkSet but I've got:"Entities in 'ProjectEntities.Links' participate in the 'Sites_have_Links' relationship. 0 related 'Sites' were found. 1 'Sites' is expected."I did set the Site relationship to "this" in the new link.
J. Pablo Fernández
That is *not* what I suggested doing. That said, setting `Link.Site` to some site *should* make that work, if you've defined the relationship property correctly.
Craig Stuntz
What I'm doing is: var link = new Link(); link.Site = this; this.Links.Add(link); and it works. How is that now what you suggested (except that maybe link.Site = this is redundant)?
J. Pablo Fernández
I didn't understand that you had an implicit `this` in your comment.
Craig Stuntz
A: 

Not sure about the answer by Craig Stuntz... The Link should be attached to the context, but adding a Link to Site.Links does not attach it automatically. You need to do db.AddToLinks(link) anyway.

But answering your question, one of the best patterns for ObjectContext management is probably the UnitOfWork pattern. By using it, you can make entities "self-aware of the scope they currently belong to". Check out this article for a detailed description and implementation samples. You can still pass the ObjectContext to the method as a parameter as you do in you example though (as a simpler implementation).

Yakimych
You are wrong. If one object is attached to a context and a second object is not, associating the two will attach the second object. Try it! Look at `second.EntityState` before and after making the association. You're also wrong about needing to call `AddToLinks`.
Craig Stuntz
Yes, I stand corrected then, thanks. And this also saved me a couple of lines of code ;)
Yakimych