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);- looks neat;
- but, context is created/released a lot sometimes, objects lose contact with context;
-
Using context in place:
using(Entities ctx = new Entities()) { Product[] ps = ctx.Product.ToArray(); // ... ctx.SaveChanges(); }- effective
- but, code becomes messy
-
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.
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: