entity framework在db.SaveChanges()期间创建新数据行

根据本教程创建AngularJS应用程序: http : //jphoward.wordpress.com/2013/01/04/end-to-end-web-app-in-under-an-hour/

类别:

public class Todo { public int ID { get; set; } public virtual Status Status { get; set; } } public class Status { public int ID { get; set; } public string Type { get; set; } } 

function是单击一个按钮,它会更改状态。 单击该按钮时,所有正确的内容都将传递到Visual Studio。 最初它根本没有更新。 经过一些研究后,我发现了一些强制更改的方法,但是在db.SaveChanges()中,它向Status添加了一个具有相同“Type”的新行,只是从最后一个处获得的递增ID。

调用update的JS:

 Api.Todo.update({ id: todoID }, todo, function () { $location.path('/'); }); 

哪个命中VS这个function:

 private DataContext db = new DataContext(); // PUT api/Todo/5 HttpResponseMessage PutTodo(int id, Todo todo) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != todo.ID) { return Request.CreateResponse(HttpStatusCode.BadRequest); } // Found a stack overflow that mentioned that you need to check for things already being tracked var entry = db.Entry(todo); if (entry.State == EntityState.Detached) { var set = db.Set(); Todo attachedEntity = set.Find(todo.ID); // You need to have access to key if (attachedEntity != null) { // The following code does not update any changes to the foreign keys var attachedEntry = db.Entry(attachedEntity); attachedEntry.CurrentValues.SetValues(todo); db.Entry(attachedEntity).State = EntityState.Modified; // When this didn't work, I tried just changing the status on the already attached entity //attachedEntity.Status = todo.Status; //db.SaveChanges(); // However when it hit SaveChanges() it created a new row in the Status table. } else { //This code was never hit entry.State = EntityState.Modified; // This should attach entity } } try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } 

我即将结束我的能力,并希望得到一些帮助或指导。

 public class Todo { public int ID { get; set; } //Foreign key public int StatusID { get; set; } //<====Add this line public virtual Status Status { get; set; } } 

发布数据时更新外键属性,而不是导航属性

另外,请检查:为什么entity framework将现有对象重新插入到我的数据库中? http://msdn.microsoft.com/en-us/magazine/dn166926.aspx