public void DAO_AttachTest() { #region Long term context. It is stored in GenericDAO.Context property // First we get CommonContext from GenericDAO to check the entity states... DbContext dbContext = ((GenericDaoEntityFramework <UserProfile, Int64>)userProfileDao).Context; // 1) We look for an userProfile (it was previously created in MyTestInitialize(); UserProfile user = userProfileDao.Find(userProfile.usrId); // Check the user is in the context (from Generic DAO) now after the Find() method execution Assert.AreEqual(dbContext.Entry(user).State, EntityState.Unchanged); // 2) We are going to delete the previously recovered userProfile userProfileDao.Remove(user.usrId); // Check the user is not in the context now (EntityState.Detached notes that entity is not tracked by the context) Assert.AreEqual(dbContext.Entry(user).State, EntityState.Detached); // The user was deleted from database Assert.IsFalse(userProfileDao.Exists(user.usrId)); // 3) So, the user entity is already in memory, but it does not exist neither in the context nor the database. // Now, if we attach the entity it will be tracked again by the context... userProfileDao.Attach(user); // EntityState.Unchanged = entity exists in context and in DataBase with the same values Assert.AreEqual(dbContext.Entry(user).State, EntityState.Unchanged); // ... and stored in database too Assert.IsTrue(userProfileDao.Exists(user.usrId)); #endregion #region Short Term Context (context is disposed after using{} block) user = null; // If we retrieve the user within a short term context it will only be tracked by the local-context // inside the block. It will not be within the generic context using (MiniPortalEntities shortTermContext = new MiniPortalEntities()) { DbSet <UserProfile> userProfiles = shortTermContext.UserProfiles; user = (from u in userProfiles where u.usrId == userProfile.usrId select u).FirstOrDefault(); Assert.AreEqual( shortTermContext.ChangeTracker.Entries <UserProfile>().FirstOrDefault().State, EntityState.Unchanged); } // EntityState.Detached notes that entity is not tracked by the context Assert.AreEqual(dbContext.Entry(user).State, EntityState.Detached); #endregion }