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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With