将数据库上下文放在静态类库中的优缺点 [英] Pros and Cons of putting a db context in static class library

查看:122
本文介绍了将数据库上下文放在静态类库中的优缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个静态类库来处理重复的多上下文任务。创建一个EF数据库上下文作为静态类的成员是不好的做法吗?



DB上下文是为了理由而被处理的。让他们经常保持连接池流动,可能(这里我猜测)确保表不保持锁定。



所以我邀请麻烦有一个静态类中的数据库环境,或者是我反思这个吗?

解决方案

IMO这绝对不是你想做的事情。



锁定实际上并不是您要在这里遇到的主要问题。 EF只会在保存更改通话的持续时间内锁定(实际上,大多数其他ORM使用的部分承诺交易使用跟踪图表的最大好处之一)。




We have a static class library to deal with repeated multi-contextual tasks. Is it bad practice to create an EF db context as member of a static class?

DB contexts are meant to be disposed of for a reason. Having them disposed frequently keeps the connection pool "flowing" and probably (here I'm speculating) assures that tables don't remain locked.

So am I inviting trouble having a db context in a static class or am I overthinking this?

解决方案

IMO this is definitally not something you want to be doing.

Locking isn't actually the main problem you are going to have here. EF will only lock for the duration of a save changes call (its actually one of the big benefits of using a tracking graph over partially committed transactions which most other ORMs use).

What is going to cause you greif is the tracking graph itself. How EF works (in most cases) is that it keeps a copy of every entity its ever seen and loops through them to find whats changed and run a process called fixups which makes navigation properties work with backlinks. This process loops through every entity the context has ever seen and is called on a bunch of operations (add, attach, delete, save, query and a few others). This means if the tracking graph is large, this process can take quite a bit of time. If you keep your context alive forever the tracking graph size tends toward the size of your database, making it unwieldy and slow.

这篇关于将数据库上下文放在静态类库中的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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