实体框架在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; }

}

功能是单击按钮并更改状态。单击该按钮时,所有正确的内容都将传递给Visual

Studio。最初它根本没有更新。经过一些研究,我发现了一些强制更改的方法,但是在db.SaveChanges()处,它向Status添加了一个新行,该行具有相同的“类型”,只是最后一个ID的增量ID。

调用update的JS:

Api.Todo.update({ id: todoID }, todo, function () {

$location.path('/');

});

在此功能上打VS:

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>();

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; }

}

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

另外,请检查以下内容:为什么实体框架将现有对象重新插入到我的数据库中? http://msdn.microsoft.com/zh-

CN/magazine/dn166926.aspx

以上是 实体框架在db.SaveChanges()期间创建新的数据行 的全部内容, 来源链接: utcz.com/qa/422532.html

回到顶部