简体   繁体   English

实体框架插入到具有外键的主表和子表中

[英]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.

相关问题 实体框架未将父ID映射为子表中的外键 - Entity Framework not mapping parent id as foreign key in child table 使用实体框架使用外键将不同的记录插入表中 - Insert distinct record into table with foreign key using Entity Framework 实体框架6更新表并插入到外键相关表中 - Entity Framework 6 update a table and insert into foreign key related tables 实体框架:在Update表中插入外键行 - Entity Framework: Insert foreign key rows when Update table 实体框架-尝试使用外键插入表中,EF尝试使用主键插入原始表中 - Entity Framework - trying to insert into a table with a foreign key, EF attempts to insert into the original table with the primary key 实体框架一个表中有两个外键 - Entity Framework Two foreign key in one table 实体框架外键多表映射 - Entity Framework Foreign Key multiple table mapping 实体框架继承:同表中的外键 - Entity Framework Inheritance: Foreign Key in the same table 如何在ASP.NET MVC中使用实体框架在父表中创建外键并将其分配给子表 - How to create the foreign key in the parent table and assign it to the child table using entity framework in asp.net mvc 将数据插入作为主键外键一部分的表中 - 实体框架 - Insert data into table which have as part of primary key foreign key - Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM