An entities that create entities using Entity Framework
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.AddToLink开发者_StackOverflows(link);
}
}
or do you use another pattern?
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.
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).
精彩评论