public static void PlayWithDetatch() { SoftUniEntities softUniEntities = new SoftUniEntities(); Employee newEmployee = new Employee { FirstName = "Vladimir", LastName = "Georgiev", JobTitle = "Technical Trainer", DepartmentID = 1, HireDate = new DateTime(2013, 12, 16), Salary = 10000 }; softUniEntities.Employees.Add(newEmployee); softUniEntities.SaveChanges(); // Now the employee is stored in the database. Let's print its department Console.WriteLine(newEmployee.Department); // prints "null" // Find the employee by primary key --> returns the same object (unmodified) // Still prints "null" (due to caching and identity resolution) var employeeById = softUniEntities.Employees.Find(newEmployee.EmployeeID); Console.WriteLine(employeeById.Department); // null (due to caching) // Find the product by query still uses "identity resolution" (caching) var employeeFromDb = (from emp in softUniEntities.Employees where emp.EmployeeID == newEmployee.EmployeeID select emp).FirstOrDefault(); Console.WriteLine(employeeFromDb.Department); // null (due to caching) // Detach the object from the context --> remove it from the cache ((IObjectContextAdapter)softUniEntities).ObjectContext.Detach(newEmployee); // This change will not be tracked by the context newEmployee.FirstName = "Vlado"; // This will make no changes in the DB (detatched objects are not tracked) softUniEntities.SaveChanges(); // Now find the product by primary key (detached entities are not cached) var detachedEmployee = softUniEntities.Employees.Find(newEmployee.EmployeeID); Console.WriteLine(detachedEmployee.Department); // works (no caching) }
/// <summary> /// Create a new Employee object. /// </summary> /// <param name="employeeID">Initial value of the EmployeeID property.</param> /// <param name="lastName">Initial value of the LastName property.</param> /// <param name="firstName">Initial value of the FirstName property.</param> public static Employee CreateEmployee(global::System.Int32 employeeID, global::System.String lastName, global::System.String firstName) { Employee employee = new Employee(); employee.EmployeeID = employeeID; employee.LastName = lastName; employee.FirstName = firstName; return employee; }
/// <summary> /// Deprecated Method for adding a new object to the Employees EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// </summary> public void AddToEmployees(Employee employee) { base.AddObject("Employees", employee); }