簡體   English   中英

EF 4.0自我跟蹤實體,預期更新正在轉換為插入

[英]EF 4.0 Self-Tracking Entities, intended updates are being translated into inserts

我們假設下面的方法存在於WCF服務中。 UI檢索Status對象的實例,並使用此方法對服務進行后續調用。 它不是像我期望的那樣將狀態分配給用戶,而是嘗試插入狀態。 我究竟做錯了什么?

void Method(Status status)
{
    //not sure if this is even needed, the status never changed
    context.Statuses.ApplyChanges(status);

    //get the first user from the database
    User user = context.Users.Where(u => u.Id = 1).First();

    //set user status to some existing status
    user.Status = status;

    //this throws an exception due to EF trying to insert a new entry
    //into the status table, rather than updating the user.StatusId column.
    context.SaveChanges();
}

試試這個:

        using (Entities ctx = new Entities())
        {
            ctx.Statuses.Attach(status);

            ObjectStateEntry entry = ctx.ObjectStateManager.GetObjectStateEntry(status);
            entry.ChangeState(EntityState.Modified);

            //get the first user from the database
            User user = ctx.Users.Where(u => u.Id = 1);

            //set user status to some existing status
            user.StatusID = status.StatusID;

            ctx.SaveChanges();
        }

如果您有興趣,這里有一個關於CRUD with Entity Framework教程

問題是您正在使用附加用戶。 當STE附加到上下文時,它的行為與任何其他實體完全相同。 其自我跟蹤機制的更多內容未激活。 因此,在將狀態設置為用戶之前,必須將狀態附加到上下文,否則它將作為必須插入的新實體進行跟蹤:

void Method(Status status)
{
    User user = context.Users.Where(u => u.Id = 1).First();

    context.Attach(status);
    user.Status = status;

    context.SaveChanges();
}

必須寫一個答案,因為我還不能評論另一個答案(代表得分<50)[ 有些奇怪的不正確,但我明白為什么就是這樣 ]因為我想為@ Ladislav的回答添加一些清晰度。

來自WCF調用的Status對象並非來自您用於查找User對象的相同context ,因此跟蹤代碼不會與該上下文一起修復。 這就是為什么附加它將允許您保存賦值而不考慮context認為status是需要插入數據庫的新實體。

暫無
暫無

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

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