Reputation: 910
I have 2 model entities like the one below "User" entity is the main table and "UserContacts" is the one which is having the foreign key. The GUI is having input fields to accept UserName and Password, the user has an option to add "n" number of contact number that he have. How can i make insert to parent table child table using entity frame work.
For example if i get the values in User entity as the one below. Please help me to solve this issue.
UserName = "ABC", Password = "123"
& UserContacts = { UserId = <Primary key of User entity>, PhoneNumber = 1234567890 },
{ UserId = <Primary key of User entity>, PhoneNumber = 9087654321 },
{ UserId = <Primary key of User entity>, PhoneNumber = 5412309876 }
public class User
{
public int Id { get;set;}
public string UserName { get;set;}
public string Password { get;set;}
public List<UserContacts> UserContacts { get; set; }
}
public class UserContacts
{
public int Id { get;set;}
public int UserId { get;set;} // Foreign key from User
public string PhoneNumber { get;set;}
public virtual User User{ get; set; }
}
Thanks
Upvotes: 0
Views: 1606
Reputation: 1989
var user = new User(){UserName="ABC", Password="123"};
user.UserContacts = new UserContacts();
user.UserContacts.Add(new UserContacts(){ PhoneNumber = "9087654321"});
user.UserContacts.Add(new UserContacts(){ PhoneNumber = "5412309876"});
Context.Users.Add(user);
Context.SaveChanges();
Adding new child records to a parent table in entity framework 6
Upvotes: 1