2

我有上面两个表,在部门表中PersonID是表的外键PersonalInfo。我有一个 Web 表单,其中包含 FirstName、SecondName、MobileNo 和 Department 文本框。所以我在PersonID插入Department.

你能告诉我如何通过使用 linq to entityframework 来存储部门的PersonalInfoID吗?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();
4

3 回答 3

1

在 EntityFramework 中,您正在使用实体引用。因此,您不必关心 ID。您所要做的就是设置从 Department 到 PersonalInfo 的引用。EF 会处理您的 ID、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);
}

你可以看看这个博客,它很好地说明了这一点!

于 2012-08-28T07:16:05.367 回答
0
myDepartment.PersonalInfo = myRecipient;

顺便说一下,将表中的列名更改DepartmentDepartmentDepartmentName这样你就不会得到一个名为的属性Department1

于 2012-08-28T07:06:57.387 回答
0

在两个新实体关联为 Amiram Korach 指定后,您只需要以下代码之一:

    myDB.AddToPersonalInfoes(myRecipient);

    myDB.AddToDepartments(myDepartment);
于 2012-08-28T07:21:32.717 回答