Sharing DbContext between multiple methods and classes

21 בספטמבר 2014

I've been working with EntityFramework for more than 3 years and I love the technology. For many cases it simplifies the work of accessing the database. It general, it is recommended to keep EntityFramework DbContext manipulation at the DAL level and not let it propagate to higher layers (BL and Presentation) So, suppose I am using the repository pattern. The application does not access the DbContext object directly but rather is using a repository object which encapsulates all the data access logic. For example, public class LoginRepository {     public Login GetLoginByID(int loginId)     {         using (MyDbContext context = new MyDbContext())         {             var login = context.Logins.Where(l => l.ID == loginId).Single();             return login;         }     }     public void DeleteLogin(int loginId)     {         using (MyDbContext context = new MyDbContext())         {             var login = GetLoginByID(loginId);             context.Logins.Remove(login);             context.SaveChanges();         }     } } This is quite a straightforward implementation. Let's use it from a Main method static void Main(string args) {     try     {         LoginRepository logins = new LoginRepository();         logins.DeleteLogin(1);     }     catch (Exception e)     {         Console.WriteLine("ERROR: " + e.ToString());     } } Surprisingly, the following error is reported The object...