user1629434
user1629434

Reputation: 33

Insert Record into two tables with one to many relation by using linq to ado.net entity froamwork

I have above two tables and in department table PersonID is Foreign key of PersonalInfo table. I have web form which contains FirstName,SecondName,MobileNo and Department text boxes. So I am having problem to insert PersonID into Department.

Can you please let me know how can I store ID of PersonalInfo into PersonID of department by using linq to entityframework?

This is my code:

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();

Upvotes: 2

Views: 2040

Answers (3)

Amiram Korach
Amiram Korach

Reputation: 13286

myDepartment.PersonalInfo = myRecipient;

By the way, change the column name Department in the Department table to DepartmentName, so you won't get a property named Department1

Upvotes: 0

Pilgerstorfer Franz
Pilgerstorfer Franz

Reputation: 8359

In EntityFramework you are working with entities and references. So you don't have to care about IDs. All you have to do is to set a reference from Department to PersonalInfo. EF will take care about your IDs, PKs and FKs!

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);
}

You may have a look at this blog, which illustrates this very nice!

Upvotes: 1

Russell Yan
Russell Yan

Reputation: 193

And you only need one of following code after the two new entities are associated as Amiram Korach specified:

    myDB.AddToPersonalInfoes(myRecipient);

    myDB.AddToDepartments(myDepartment);

Upvotes: 0

Related Questions