Work with entity map, preferred method?

Suppose we created an Entities model, what is the preferred way to work with it? I personally cannot decide.

  • 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, the context is created / released sometimes, objects lose contact with the context;
  • Using context in place:

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

  • Extension Methods:

     using(Entities ctx = new Entities()) { Product[] ps = ctx.GetProducts(); // ... ctx.UpdateProduct(p); } 

In fact, now I'm trying to approach approach No. 4, implementing utility methods as an extension of the context. Therefore, I can use one context and make many calls in this context.

+6
source share
3 answers

Generally, use whatever is appropriate for your needs, which can be maintained and appropriate for the complexity of your application. A few points you should think about:

  • Never exchange context between requests , use context for each request, per action or method depending on your needs.
  • If you want to unit test your application, you may find that static methods, and sometimes extension methods, can be a problem. But testing an application with EF is a separate issue .
  • If you want to change or insert more elements in one unit of work, you may find that the context for each method is not right for you.
  • Many developers like to use the repository template to share access to EF functions from the rest of the application. This has its pros and cons .
+2
source

When developing web applications, I use the general context that is created for each web request. Then you can use the "ModelAdapter" approach and save the encapsulation, but work in the same context. I used this a lot and did not experience any problems.

+6
source

As a rule, I would go for an implementation where the complexity of working with EF is abstracted using the Repository template, but the context is alive as long as I need it. (Scenario 3)

By β€œas long as I need it,” I mean while the service call is being executed. I do not want the ObjectContext persist through multiple service calls, as I would have to deal with its state. The cost of creating a new ObjectContext negligible.

I think that in many ways your ModelAdapter also abstracts the complexities of EF, however, based on its static nature, you may / may run into problems in parallel scripts if you decide to keep the ObjectContext . The way it is currently implemented may not give you the flexibility you need for more complex queries (for example, for the Order ↔ OrderDetail ↔ Product connection).

0
source

Source: https://habr.com/ru/post/887716/


All Articles