通过使用linq到ado.net实体froamwork将Record插入到具有一对多关系的两个表中

时间:2012-08-28 07:00:44

标签: c# linq entity-framework-4 linq-to-entities

我有两个表,在部门表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();

3 个答案:

答案 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);