实体框架4 - winform应用程序中的上下文的寿命/范围 [英] Entity Framework 4 - lifespan/scope of context in a winform application

查看:103
本文介绍了实体框架4 - winform应用程序中的上下文的寿命/范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于有关EF4上下文生命周期的另一个问题,对不起,我一直在想这一段时间,我似乎没有找到答案。我不太熟悉很多模式或过于复杂的东西(在我看来),所以我想保持简单。



我使用ASP.NET应用程序,其中上下文由每个http请求管理,这在我看来是一个非常好的方法。



但是,我正在使用一个winforms应用程序,我有时有交易或者如果我只是为每个查询创建上下文,报表将不会很好。不是说这个性能问题是一个非常有问题的事情,我只是想听听ASP.NET中针对winform的HTTP请求是否有简单的策略?

解决方案

不要为每个查询创建上下文。同时,不要创建在Form(或您的应用程序)的整个生命周期中使用的上下文。



创建一个上下文单一工作单位(可以包含许多查询)。



这样你就可以将所有更改封装在上下文中,并让Entity Framework在一个很小的事务中包装数据库调用,而无需自己担心。 / p>

我更喜欢从实体上下文中抽取Repository和Work of Work模式,以便我们可以独立使用它们(这使得一切都非常清楚)。 MSDN实际上有一个很好的文章细节:



MSDN - 使用实体框架4的存储库和工作单元模式


Sorry for yet another question about EF4 context lifespan, but I've been wondering about this for a while and I do not seem to find the answer. I'm not very familiar with lots of patterns or overcomplicated stuff (in my point of view) so I want to keep it simple.

I work with an ASP.NET application where the context is managed by each http request which is a very good approach in my opinion.

However I'm now working with a winforms application and I sometimes have transactions or reports that will not perform very well if I simply create the context for each query. Not that this performance issue is a very problematic thing, I just want to hear if there's a simple strategy as per HTTP request in ASP.NET for winforms?

解决方案

Don't create a context for each query. At the same time, don't create a context that gets used for the entire lifetime of a Form (or your application).

Create a context for a single Unit of Work (which can encompass many queries).

That way you have all of your changes encapsulated in the context and you let Entity Framework wrap the database calls in a pretty little transaction without having to worry about it yourself.

I prefer to abstract the Repository and Unit of Work patterns out of the Entity Context so that I can use them independently (which makes everything very clear). MSDN actually has a decent article on the details:

MSDN - Using Repository and Unit of Work patterns with Entity Framework 4

这篇关于实体框架4 - winform应用程序中的上下文的寿命/范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆