Reputation: 33
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
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
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
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