1

EntityFrameworkを使用してデータベースにレコードを追加する必要があります。私はこの構文を使用するのは初めてなので、コードを正しく記述する方法がわかりません(以下が私の最善の推測です)。

まず、エージェントは自分の情報をテーブルに挿入する必要がありAgentます。このテーブルは、として知られる自己インクリメント主キーを生成しますSymNumberSymNumber次に、それを取得して、テーブルに挿入するための主キーとして使用する必要がありAgentIdentificationます。

このコードを数回実行しましたが、エラーは発生しませんが、単体テストを使用してコードをテストしているため、エージェントが適切に追加されているかどうかを確認できません。第二に、私は最初の挿入後にテーブルSymNumberによって生成されたものを正しく取得していないという事実を知っています。Agentこれは、0に設定されたLinqコードのint値であり、挿入 SymNumber中に変更されません。AgentIdentification

どんな助けでも大歓迎です!

        AgentResourcesEntities _db = new AgentResourcesEntities();

        try
        {
            Agent agent = new Agent();
            agent.EntityType = "P";
            agent.FirstName = agentNewTraining.FirstName;
            agent.LastName = agentNewTraining.LastName;
            agent.LastChangeOperator = agentNewTraining.Requestor;
            agent.LastChangeDate = DateTime.Now;
            if (!String.IsNullOrEmpty(agentNewTraining.NameSuffix)) agent.NameSuffix = agentNewTraining.NameSuffix;

            _db.Agent.AddObject(agent);

            AgentIdentification agentIdentification = new AgentIdentification();
            agentIdentification.SymNumber = agent.SymNumber;
            agentIdentification.ReferenceType = "S";
            agentIdentification.DummyReference = 0;
            agentIdentification.LastChangeOperator = agentNewTraining.Requestor;
            agentIdentification.LastChangeDate = DateTime.Now;

            _db.AgentIdentification.AddObject(agentIdentification);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
4

2 に答える 2

1

最初に電話する必要があります

_db.SaveChanges();

変更を永続化するため。

ただし、同期(新しく生成された値を取得)する場合は、コンテキストに追加した直後agent.SymNumberに呼び出す必要があります。SaveChanges()

したがって、コードは次のようになります。

/// ...... ////
_db.Agent.AddObject(agent);
_db.SaveChanges();

AgentIdentification agentIdentification = new AgentIdentification();
agentIdentification.SymNumber = agent.SymNumber;  // sym number is now synchronized from DB
 ///...../////

_db.AgentIdentification.AddObject(agentIdentification);
_db.SaveChanges();

ただし、SymNumberが外部キーである場合、AgentIdentificationhasはあるインスタンスへの参照を持つことができ、それらのインスタンスをその参照に関連付けることができ、途中でAgentその追加を呼び出す必要はありません。SaveChanges()

于 2013-01-04T19:35:58.227 に答える
0

_db.SaveChanges()挿入してからお電話ください。

于 2013-01-04T19:28:03.740 に答える