Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.AddToLinks(link);
    }
}

or do you use another pattern?

like image 304
pupeno Avatar asked Jul 26 '26 00:07

pupeno


2 Answers

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.

like image 117
Craig Stuntz Avatar answered Jul 28 '26 14:07

Craig Stuntz


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).

like image 43
Yakimych Avatar answered Jul 28 '26 16:07

Yakimych