The problem is that your Person entities are still attached to context created in GetPersons. If you want to work with attached entities you have to use same context instance in both select and update operations. You have two choices to solve your problem.
1) Correctly handled attached entities
public class Program
{
[STAThread]
static void main()
{
using (DataAccessClass dal = new DataAccessClass())
{
List<Person> list = dal.GetPersons();
Person p = list[0];
p.LastName = "Changed!";
dal.Save();
}
}
}
public class DataAccessClass : IDisposable
{
private MyDBEntities _context = new MyDBEntities();
public List<Person> GetPersons()
{
return _context.Persons.ToList();
}
public void Save()
{
// Context tracks changes on your entities. You don't have to do anything. Simply call
// SaveChanges and all changes in all loaded entities will be done in DB.
_context.SaveChanges();
}
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
}
2) Don't use attached entities
public class Program
{
[STAThread]
static void main()
{
DataAccessClass dal = new DataAccessClass())
List<Person> list = DataAccessClass.GetPersons();
Person p = list[0];
p.LastName = "Changed!";
dal.Update(p);
}
}
public class DataAccessClass
{
public static List<Person> GetPersons()
{
// Closing context will detach entities
using (MyDBEntities context = new MyDBEntities())
{
return context.Persons.ToList();
}
}
public void Update(Person p)
{
using (MyDBEntities context = new MyDBEntities())
{
context.Persons.Attach(p);
// Detached entities don't track changes so after attaching you have to say
// what changes have been done
context.ObjectStateManager.ChangeObjectState(p, System.Data.EntityState.Modified);
context.SaveChanges();
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…