2015-01-07 80 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

相關問題