实体框架在db.SaveChanges()期间创建新数据行

时间:2014-07-22 19:08:46

标签: c# angularjs entity-framework

根据本教程创建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添加了一个新行,它具有相同的' Type',只是从最后一个增加的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);
    }

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

1 个答案:

答案 0 :(得分:3)

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/en-us/magazine/dn166926.aspx