从另一个表生成一个表 - MVC5

时间:2015-08-19 12:51:37

标签: c# asp.net database visual-studio-2013 asp.net-mvc-5

我是MVC5和.NET的新手。我正在使用ASP应用程序用户并有一个额外的表患者:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid PatientId { get; set; }

[ForeignKey("User")]
    [Display(Name = "User Id")]
    public string UserId { get; set; }
    public virtual ApplicationUser User { get; set; }

我的AccountController是:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    { 

        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                UserName = model.Email,
                Email = model.Email,
                Title = model.Title,
                FirstName = model.FirstName,
                LastName = model.LastName,
                DOB = model.DOB,
                Gender = model.Gender,
                ContactNumber = model.ContactNumber,
                Address1 = model.Address1,
                Address2 = model.Address2,
                Address3 = model.Address3,
                County = model.County,
                Postcode = model.Postcode
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {

             //Create patient ID
             Patient patient = new Patient();
             patient.PatientId = Guid.NewGuid();
             patient.UserId = user.Id;
             db.Patients.Add(patient);

                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }
        return View(model);
    }

我正在尝试注册时创建一个患者实例,该实例将生成一个患者ID以及引用的外键用户ID。但是,当我在注册时注册新用户时,不会创建相应的患者。 任何建议都将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:1)

db.Patients.Add(patient);旁边的

您需要调用DBContext的savechanges来确认de transaction,在您的情况下,是对患者的添加。