Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with entity framework, preferred way?

Suppose we have created Entities model, what is preferred way to work with it? I'm personally couldn't make up my mind..

  1. 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;
  2. Using context in place:

    using(Entities ctx = new Entities())
    {
            Product[] ps = ctx.Product.ToArray();
    
            // ...
    
            ctx.SaveChanges();
    }
    
    • effective
    • but, code becomes messy
  3. Mixed mode, compromise?

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

like image 449
Petr Abdulin Avatar asked May 10 '11 12:05

Petr Abdulin


2 Answers

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.

like image 77
Lee Gunn Avatar answered Sep 28 '22 02:09

Lee Gunn


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:

  • Never share context among requests, use a context per request, per action or per method depending on your needs.
  • If you want to unit test your application you can find that static methods and sometimes also extension methods can be a problem. But testing application with EF is a separate problem.
  • If you want to modify or insert more items in a single unit of work you can find that a context per method is not what you need
  • Many developers like to use the repository pattern to separate access to EF features from the rest of the application. It has its own pros and cons.
like image 39
Ladislav Mrnka Avatar answered Sep 28 '22 04:09

Ladislav Mrnka