如何将主键值从表保存到另一个表?

时间:2015-02-04 12:42:22

标签: c#

我想将人员表中的 PersonId 值保存到密码表,但我遇到了问题。我的问题是它在密码表上的 PersonId 上保存零,而不是保存在person表中自动生成的值(personId)。将不胜感激。

查看模型

public class UserVM
  {
     public int PersonID { get; set; }        
     public string FirstName { get; set; }       
     public string LastName { get; set; }      
     public string UserName { get; set; }       
     public string Password1 { get; set; }     
 }

密码

  public partial class Password
{       
public int BusinessEntityID { get; set; }       
public string Password1 { get; set; }
public int PersonID { get; set; }
 }

   public partial class Person1
  {

public int PersonID { get; set;     
public string Title { get; set; }
public string FirstName { get; set; }       
public string LastName { get; set; }      
public string UserName { get; set; }
public Nullable<int> UserAuthRoleId { get; set; }
 public virtual ICollection<Password> Passwords { get; set; }
 }

控制器

  // POST: api/Person1
[ResponseType(typeof(Person1))]
public IHttpActionResult PostPerson1(UserVM vm)
{
    var pers = new Person1
    {
        Title = vm.Title,
        FirstName = vm.FirstName,
        LastName = vm.LastName,
        UserName = vm.UserName,               
    };
    var word = new Password();
    using (var context = new VybeEstoreEntities1())
    {
       context.People1.Add(pers);
        word.PersonID = pers.PersonID;                            
        word.Password1 = vm.Password1;               
        context.Passwords.Add(word);
        context.SaveChanges();
     }

截图

人员表

enter image description here

密码表

enter image description here

1 个答案:

答案 0 :(得分:2)

假设您正在使用EntityFramework Code First,您将需要声明Person1和Password之间的关系。例如:

public partial class Person1
{
    public int PersonID { get; set;     
    public string Title { get; set; }
    public string FirstName { get; set; }       
    public string LastName { get; set; }      
    public string UserName { get; set; }
    public Nullable<int> UserAuthRoleId { get; set; }
    public virtual Password Password { get; set; }
}

然后省略手动设置word.PersonId的行,省略Password中的PersonId字段。