Reputation: 35255
Suppose we have created Entities model, what is preferred way to work with it? I'm personally couldn't make up my mind..
Using ModelAdapter :
public statiс Product[] GetProducts()
{
using(Entities ctx = new Entities())
{
return ctx.Product.ToArray();
}
}
Product[] ps = ModelAdapter.GetProducts();
// ...
ModelAdapter.UpdateProduct(p);
Using context in place:
using(Entities ctx = new Entities())
{
Product[] ps = ctx.Product.ToArray();
// ...
ctx.SaveChanges();
}
Mixed mode, compromise?
Extension methods:
using(Entities ctx = new Entities())
{
Product[] ps = ctx.GetProducts();
// ...
ctx.UpdateProduct(p);
}
Actually now, I'm trying approach #4, implementing utility methods as extensions to context. So I can use one context, and make many calls to this context.
Upvotes: 6
Views: 493
Reputation: 364409
Generally use anything that fits your needs, that is maintainable and that fits to the complexity of your application. Few points which you should think about:
Upvotes: 2
Reputation: 36031
Typically I would go for an implementation where the complexities of dealing with EF are abstracted away by using the Repository pattern, but have the context alive as long as I need it. (Scenario 3)
By "as long as I need it" I mean as long as the service call takes. I don't want the ObjectContext
to persist through multiple service calls, as I would need to deal with its state. The cost of creating a new ObjectContext
is negligible.
I think in many ways your ModelAdapter
also abstracts away EF complexities, however based on its static nature, you might/will run into problems in concurrent scenarios if you decide to persist the ObjectContext
. The way it's implemented now might not give you the flexibility you need for more complex queries (joining Order<->OrderDetail<->Product for instance).
Upvotes: 0
Reputation: 8666
When developing web applications I've been using a shared context which is created per web request. Then you can use your "ModelAdapter" approach and retain encapsulation but still operate on the same context. I've used this a lot and haven't experienced any problems.
Upvotes: 6