[英]Entity framework insert to main table and child table having foreign key
我有2個模型實體,例如下面的一個“用戶”實體是主表,“用戶聯系人”是具有外鍵的實體。 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; }
}
謝謝
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.