我有两个表,在部门表PersonID
中是PersonalInfo
表的外键。我有Web表单,其中包含FirstName,SecondName,MobileNo和Department文本框。因此,我将问题PersonID
插入Department
。
请告诉我如何使用linq to entityframework将PersonalInfo
的ID存储到PersonID
部门?
这是我的代码:
PersonalInfo myRecipient = new PersonalInfo();
myRecipient.FirstName = id_firstName.ToString();
myRecipient.SecondName = id_lastName.Text.ToString();
myRecipient.MobileNo = id_mobileNo.Text.ToString();
Department myDepartment = new Department();
myDepartment.Department1 = id_departmentName.Text.ToString();
MyEntity myDB = new MyEntity();
myDB.AddToPersonalInfoes(myRecipient);
myDB.AddToDepartments(myDepartment);
myDB.SaveChanges();
答案 0 :(得分:1)
在EntityFramework中,您正在使用实体和引用。所以你不必关心ID。您所要做的就是设置从Department到PersonalInfo的引用。 EF会照顾你的身份证,PK和FK!
try
{
// create objects, set properties ...
PersonalInfo myRecipient = new PersonalInfo();
myRecipient.FirstName = id_firstName.ToString(); // CHECK if value is valid (correct max length, ..)
// and so on ..
// set reference from Entity Department to Recipient
myDepartment.PersonalInfo = myRecipient;
myDB.AddToPersonalInfoes(myRecipient);
myDB.AddToDepartments(myDepartment);
myDB.SaveChanges();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
if (ex.InnerException!=null)
Debug.WriteLine(ex.InnerException.Message);
}
你可以看看这个blog,这说明这非常好!
答案 1 :(得分:0)
myDepartment.PersonalInfo = myRecipient;
顺便说一下,将Department
表格中的列名Department
更改为DepartmentName
,这样您就不会获得名为Department1
的属性
答案 2 :(得分:0)
在两个新实体关联为Amiram Korach后,您只需要以下代码之一:
myDB.AddToPersonalInfoes(myRecipient);
myDB.AddToDepartments(myDepartment);