猿问

如何在Entity Framework 4 .NET中更新实体

我的代码是这样的:


public class Program

{

 [STAThread]

 static void main()

 {

  DataAccessClass dal = new DataAccessClass();

  List<Person> list = dal.GetPersons();

  Person p = list[0];

  p.LastName = "Changed!";

  dal.Update(p);

 }

}


public class DataAccessClass

{

 public static List<Person> GetPersons()

 {

  MyDBEntities context = new MyDBEntities();

  return context.Persons.ToList();

 }


 public void Update(Person p)

 {

  // what sould be written here?

 }

}

现在请告诉我我应该在Update()方法中写些什么?我写的所有内容都会遇到各种异常。(请注意,加载的数据已被跟踪,连接或类似的操作)


天涯尽头无女友
浏览 456回答 3
3回答

萧十郎

摘自Employee Info Starter Kit,您可以考虑以下代码片段:public void UpdateEmployee(Employee updatedEmployee)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //attaching and making ready for parsistance&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (updatedEmployee.EntityState == EntityState.Detached)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _DatabaseContext.Employees.Attach(updatedEmployee);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _DatabaseContext.ObjectStateManager.ChangeObjectState(updatedEmployee, System.Data.EntityState.Modified);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _DatabaseContext.SaveChanges();&nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答