ADO .NET实体框架问题 [英] ADO .NET Entity Framework question

查看:74
本文介绍了ADO .NET实体框架问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,在使用实体数据模型时,我们是否可以避免每次想要与数据库交互时添加代码?

Hello, when using an entity data model, can we avoid adding the code bellow everytime we want to interact with the database?

using (dbEntities ctx = new dbEntities())
{
//code
}



有没有办法在全球范围内声明在类或项目中?


Is there a way to declar this globally in a class or a project?

推荐答案

您可以使用Tadit Dash的解决方案。但你应该使用你发布的那个。仅仅因为它是由EF'的制造商推荐的,并且因为它是最佳实践(工作单元)。请阅读以下建议: http://www.adventurecoder.com/2012/01/entity -framework-best-practice.html [ ^ ]
You can use Tadit Dash''s solution. But you should use the one you posted. Simply because it''s recommended by EF''s maker, and because it is best practice (unit of work). Please read these advice: http://www.adventurecoder.com/2012/01/entity-framework-best-practice.html[^]


是的,你可以在课程级别声明它并在任何你想要的地方使用它。

Yes, you can just declare it in class level and use it wherever you want.
public class MyClass
{
    dbEntities ctx = new dbEntities()

    private void MyFunction()
    {
        // Use the object "ctx" here and do any task. 
    }
}





如果您这样做,那么该对象将不会被处置直到垃圾收集器来处理它。



但是如果你使用使用声明 [ ^ ],然后在using语句之后,对象将被释放,这将为您的应用程序带来性能优势。



If you do like this, then the object will not get disposed until Garbage Collector comes and disposes it.

But if you use using Statement[^], then just after the using statement the object will get disposed, which will be a performance advantage for your application.


这篇关于ADO .NET实体框架问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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