从尚未保存的实体获取ID

时间:2016-11-13 17:46:25

标签: c# asp.net entity-framework

我有一个场景,我需要在表中插入一条记录 - myPerson Entity来获取personID(int identity)。然后我需要获取该personID并将其添加到familyAdmin.personID。

我希望在一个db.SaveChange()中完成所有这些操作。

因为person实体是userAdmin实体的一部分,有没有办法在一个实现?

目前我如何设置:

userAdmin familyAdmin = new userAdmin();
familyAdmin.signupDate = DateTime.Today;
familyAdmin.lastLogin = DateTime.Today;
familyAdmin.registrationID = newReg.registrationID;

person myPerson = new person();
myPerson.personName = newReg.name;
myPerson.personEmail = newReg.email;
myPerson.personPhone = newReg.phone;
myPerson.personPhoneCarrier = newReg.carrierName;
myPerson.personDOB = newReg.dob;
myPerson.familyID = familyAdmin.familyID;
myPerson.personTypeID = newReg.personTypeID;

familyAdmin.personID = myPerson.personID;
familyAdmin.people.Add(myPerson);

db.userAdmins.Add(familyAdmin);
db.SaveChanges();

此选项目前无效。执行此选项时没有生成错误。我只得到0而不是1,2,3等。

插入人员表正在运行,正在生成ID。就在我尝试检索该ID以便在我获得0的同时插入UserAdmin表时。

我必须做这样的事情:

person myPerson = new person();
myPerson.personName = newReg.name;
myPerson.personEmail = newReg.email;
myPerson.personPhone = newReg.phone;
myPerson.personPhoneCarrier = newReg.carrierName;
myPerson.personDOB = newReg.dob;
myPerson.familyID = familyAdmin.familyID;
myPerson.personTypeID = newReg.personTypeID;

db.person.Add(myPerson);
db.SaveChanges();


userAdmin familyAdmin = new userAdmin();
familyAdmin.signupDate = DateTime.Today;
familyAdmin.lastLogin = DateTime.Today;
familyAdmin.registrationID = newReg.registrationID;
familyAdmin.personID = myPerson.personID;

db.userAdmins.Add(familyAdmin);
db.SaveChanges();

部分EDMX图片:

enter image description here

1 个答案:

答案 0 :(得分:3)

由于这两行,第一个选项无效:

myPerson.familyID = familyAdmin.familyID;

familyAdmin.personID = myPerson.personID;

这些行不是必需的,因为您正在检查未在数据库中创建的标识符。

您的代码应如下所示:

userAdmin familyAdmin = new userAdmin();
familyAdmin.signupDate = DateTime.Today;
familyAdmin.lastLogin = DateTime.Today;
familyAdmin.registrationID = newReg.registrationID;

person myPerson = new person();
myPerson.personName = newReg.name;
myPerson.personEmail = newReg.email;
myPerson.personPhone = newReg.phone;
myPerson.personPhoneCarrier = newReg.carrierName;
myPerson.personDOB = newReg.dob;
// myPerson.familyID = familyAdmin.familyID; Not necessary
myPerson.personTypeID = newReg.personTypeID;

// familyAdmin.personID = myPerson.personID; Not necessary
familyAdmin.people.Add(myPerson);

db.userAdmins.Add(familyAdmin);
db.SaveChanges();

如果您已正确配置people实体与userAdmin实体之间的person属性之间的关系,那么使用familyAdmin.people.Add(myPerson);calling db.SaveChanges();则EF会调用{内部{1}}以便修复这两个实体之间的关系并以正确的顺序生成正确的SQL,因为它知道哪个实体需要先插入,哪个实体需要外键id。