2015-01-07 53 views
0

我有2个模型实体,如下面的“User”实体是主表,“UserContacts”是具有外键的实体。 GUI具有用于接受用户名和密码的输入字段,用户可以选择添加他拥有的“n”号联系号码。我如何使用实体框架工作插入父表子表。将实体框架插入到具有外键的主表和子表中

例如,如果我在下面的用户实体中获取值。请帮我解决这个问题。

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

感谢

回答

1
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

相关问题