Best way to initialize an entity framework context?

前端 未结 3 682
我在风中等你
我在风中等你 2020-12-08 02:30

When initialize an entity framework context.

One is to initialize at class level, such as

public class EntityContactManagerRepository
    : ContactM         


        
相关标签:
3条回答
  • 2020-12-08 03:10

    Well, the "best" way is always subjective. However, adding a UnitOfWorkScope class to the project can simplify things greatly - namely you don't have to think too much about creating the object context or persisting the Unit of Work back to the database.

    There is a great article that explains How To Create a Unit of Work Scope.

    0 讨论(0)
  • 2020-12-08 03:13

    Generally speaking: it's context per request in ASP.NET and context per window in WinForms/WPF.

    There's an article that explains quite well the reasoning behind the context per request paradigm: Entity Framework Object Context Scope

    0 讨论(0)
  • 2020-12-08 03:21

    It does matter, because the context controls the lifetime of change tracking data, and also impacts which object instances you can link together when you edit the objects, since objects on two different contexts cannot have a relationship with each other. It looks to me like the examples you're sharing come from an ASP.NET MVC application. In this case, I generally use one entity context per request, since requests are short-lived, and since it's common, when updating an object in a request, to have to fetch other objects and create relationships between them.

    On the other hand, you don't want to keep an entity context around for a long time, because it will chew up memory as it tracks changes to more and more objects.

    This may seem like an argument for the "one context per class" option, but it isn't, really. It's more like an argument for "one context per unit of work."

    0 讨论(0)
提交回复
热议问题