0

以下のメソッドが 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();
}
4

3 に答える 3

1

問題は、アタッチされたユーザーで作業していることです。STEがコンテキストにアタッチされている場合、STEは他のエンティティとまったく同じように動作します。さらに、その自己追跡メカニズムはアクティブ化されていません。したがって、ステータスをユーザーに設定する前に、コンテキストにステータスを添付する必要があります。そうしないと、挿入する必要のある新しいエンティティとして追跡されます。

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

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

    context.SaveChanges();
}
于 2011-04-11T21:05:00.093 に答える
1

代わりにこれを試してください:

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

興味のある方は、Entity Framework を使用した CRUDのチュートリアルをご覧ください。

于 2011-04-11T19:45:59.757 に答える
0

@Ladislavの回答に明確さを追加したかったので、別の回答(担当者スコア<50)についてまだコメントできないため、回答を書く必要があります[それについて奇妙なことに正しくありませんが、なぜそうなのかがわかります]。

StatusWCF 呼び出しからのオブジェクトcontextは、オブジェクトの検索に使用しているオブジェクトからのUserものではないため、追跡コードはそのコンテキストで修正されません。これが、アタッチすると、データベースへの挿入が必要な新しいエンティティであるcontextと考えることなく、割り当てを保存できる理由です。status

于 2011-05-03T18:54:00.170 に答える