2015-01-07 4 views
0

"User"엔티티가 주 테이블이고 "UserContacts"가 외래 키를 갖는 엔티티와 같은 두 개의 모델 엔티티가 있습니다. GUI는 UserName과 Password를 받아들이 기위한 입력 필드를 가지고 있으며, 사용자는 자신이 가지고있는 "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

관련 문제