Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello, when using an entity data model, can we avoid adding the code bellow everytime we want to interact with the database?
C#
using (dbEntities ctx = new dbEntities())
{
//code
}

Is there a way to declar this globally in a class or a project?
Posted
Updated 25-May-13 9:50am
v3

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[^]
 
Share this answer
 
Yes, you can just declare it in class level and use it wherever you want.
C#
public class MyClass
{
    dbEntities ctx = new dbEntities()

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


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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900