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

时间:2015-01-07 03:47:27

标签: c# asp.net-mvc entity-framework

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

例如,如果我将User实体中的值作为下面的值。请帮我解决这个问题。

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 个答案:

答案 0 :(得分: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