EF4: ObjectContext Lifetime?

前端 未结 2 892
夕颜
夕颜 2020-12-20 23:38

I am developing a WPF desktop app that uses Entity Framework 4 and SQL Compact 4. I have seen two distinct styles of Repository classes:

  • The

相关标签:
2条回答
  • 2020-12-21 00:12

    I would have thought that holding an ObjectContext open over multiple accesses would be bad practice. As soon as it becomes corrupted then you would need to recycle in and handle the corruption.

    The Repository pattern is more for abstraction of data access but doesn't necessarily map to lifetime of context.

    The unit of work pattern is more about encapsulation of one or more database/repository accesses i.e. a use case may have you adding a new Blog and then adding the first default post, this may require calling two repositories, at this point you might want to share the context and encapsulate these two commands in a transaction. Adding a second post might be done hours later and be a new context/unit of work.

    DJ is right in mentioning Context lifetimes which you'd set generally at an application level.

    0 讨论(0)
  • 2020-12-21 00:23

    The best practice is depended on how your users are going to use the application: And how your application is structured.

    if there is only one user using your application at one time, you can even create your entity context as a static instance.

    context can be used per request, per thread, per form.

    read more: http://blogs.microsoft.co.il/blogs/gilf/archive/2010/02/07/entity-framework-context-lifetime-best-practices.aspx

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