[英]Entity framework insert to main table and child table having foreign key
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. 我有2个模型实体,例如下面的一个“用户”实体是主表,“用户联系人”是具有外键的实体。 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. GUI具有输入字段以接受用户名和密码,用户可以选择添加“ n”个联系人号码。 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 谢谢
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 在实体框架6中将新的子记录添加到父表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.