简体   繁体   中英

quick linq-to-sql what would be more efficient

What is the life cycle of a data context.

MyDB_DataContext db = new MyDB_DataContext();

Is it more efficient to pass one context across several methods or create new instances of it. OR is there any reason to choose one over the other

public void DoStuff(){
    MyDB_DataContext db = new MyDB_DataContext();
    doMoreStuff()
}
private void doMoreStuff(){
    MyDB_DataContext db = new MyDB_DataContext();
    return;
}

VS

public void DoStuff(){
    MyDB_DataContext db = new MyDB_DataContext();
    doMoreStuff(db)
}
private void doMoreStuff(MyDB_DataContext db){            
    return;
}

There's no hard-and-fast rules, but to give you some context, DataContexts should generally be per-request if you're writing a website. Don't create it all the time, but what you definitely don't want to do is carry around the DataContext as a singleton.

Edit: %s/session/request/g

well in my opinion you can use one instance in all method because everytime when you call instance new method the memory get refresh and your instances get new value without effecting your recent value.well datacontext is only used to make object for dataclasses so that we can easily call any table or stored procedure in any method.

As you can declare datacontext as a global variable.its one object works fine for all methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM