簡體   English   中英

實體框架在db.SaveChanges()期間創建新的數據行

[英]Entity Framework Creating new data rows during 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/en-us/magazine/dn166926.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM