1

我需要使用实体框架将记录添加到数据库中。由于我是使用这种语法的新手,我不确定如何正确编写代码(以下是我的最佳猜测)。

首先,代理必须将他们的信息插入到Agent表中。此表生成一个自增主键,称为SymNumber. 然后我需要将SymNumber其用作插入AgentIdentification表的主键。

我已经多次运行此代码,但没有出现错误,但是由于我正在使用单元测试来测试代码,因此我无法确定是否正确添加了代理。其次,我知道一个事实,即在第一次插入后我没有正确抓取表格SymNumber生成的内容。Agent这是在 Linq 代码中设置为 0 的 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

First you need to call

_db.SaveChanges();

to get your changed persisted.

But if you want also synchronize (get the new generated value) your agent.SymNumber you will need to call SaveChanges() right after adding it to context.

So the code will be like:

/// ...... ////
_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();

But if SymNumber is foreign key so the AgentIdentification has could have reference to some Agent instance, you can just tie those instances with that reference and would not need to call that additional SaveChanges() in the middle.

于 2013-01-04T19:35:58.227 回答
0

_db.SaveChanges()插入后调用。

于 2013-01-04T19:28:03.740 回答