coto2
coto2

Reputation: 179

Generating a table from another table - MVC5

I'm very new to MVC5 and .NET. I am using the ASP Application User and have a additional table Patient:

[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; }

My AccountController is:

    [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);
    }

I am trying to upon registration create an instance of patient which will generate a patientId along with the referential Foreign Key user id. However when I register a new user in registration no corresponding patient is created. Any advice would be greatly appreciated.

Thanks

Upvotes: 0

Views: 51

Answers (1)

Julito Avellaneda
Julito Avellaneda

Reputation: 2385

next to the line db.Patients.Add(patient); you need to call the savechanges of the DBContext to confirm de transaction, in your case, the add to the Patient.

Upvotes: 1

Related Questions