我是否需要.SaveChanges()才能获得外键的ID?

时间:2011-07-19 02:05:22

标签: entity-framework-4

在下面的代码中,我正在保存一个新人,然后抓住该人的ID以在相关地址记录中用作FK。 PK被定义为db中的标识列。我的问题,我需要调用dc.SaveChanges();将人物添加到对象集后?有没有办法避免前往数据库获取ID,然后将其作为FK传递给地址?我可以将两个savechanges()一起滚动到一个操作中吗?

            PlaygroundEntities dc = new PlaygroundEntities();

            Person person = new Person
                                {
                                    FirstName = txtFirstName.Text,
                                    LastName = txtLastName.Text
                                };

            dc.People.AddObject(person);
            dc.SaveChanges();

            Address address = new Address
                                  {
                                      PeopleId = person.Id,
                                      Address1 = txtAddress.Text,
                                      City = txtCity.Text,
                                      State = txtState.Text,
                                      ZipCode = txtZipCode.Text
                                  };

            dc.Addresses.AddObject(address);
            dc.SaveChanges();

2 个答案:

答案 0 :(得分:6)

没有办法检索person.Id没有查询,只要person.Id是自动生成密钥。 但是,如果获得person.Id的目的只是为了创建地址,你不需要解决那个人。你只需要添加地址的人如下:

    Person person = new Person 
                    { 
                       FirstName = txtFirstName.Text, 
                       LastName = txtastName.Text, 
                       Address = new Address
                                 { 
                                    Address1=txtAddress.Text, 
                                    City=txtCity.Text, 
                                    State=txtState.Text, 
                                    ZipCode=txtZipCode.Text 
                                 }
                     }

dc.People.AddObject(person);
dc.SaveChanges();

就是这样。

答案 1 :(得分:0)

Person person = new Person
    {
                                FirstName = txtFirstName.Text,
                                LastName = txtLastName.Text
                            };


        Address address = new Address
                              {
                                  People = person,
                                  Address1 = txtAddress.Text,
                                  City = txtCity.Text,
                                  State = txtState.Text,
                                  ZipCode = txtZipCode.Text
                              };

        dc.Addresses.AddObject(address);
        dc.SaveChanges();

根据您的示例,添加对象引用,然后保存一次,而不是保存和添加ID。