I want to use last inserted id from database, but that Id is in string format. Is there any way I can get last inserted string ID?
Every time I am using
p.UserId = db.AspNetUsers.Max(m => m.Id);
but it is returning wrong results. I think it is string so max won't work. Can anyone please suggest how to solve this problem?
Table structure:
- Patient: ID (PK), UID (fk of UserLogin), Name
AspNetUsers table:
CREATE TABLE [dbo].[AspNetUsers]
(
[Id] NVARCHAR(128) NOT NULL,
[Email] NVARCHAR (256) NULL,
)
Patient table:
CREATE TABLE Patient
(
PatientId INT IDENTITY(1,1) PRIMARY KEY,
PId AS 'P' + RIGHT('00000' + CAST(PatientId AS NVARCHAR(10)), 10) PERSISTED,
UserId NVARCHAR(128) FOREIGN KEY REFERENCES AspNetUsers(Id)
)
Example ID is in format like this : 62d8d072-5261-4aaf-b552-d75453cc3421
This is the code , first I am getting value from view in AspNetUsers table , therefore it will generate id in table and I want to use that Id for my Patient table.
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public async Task<ActionResult> SignUp(Patientview pv)
{
ClinicDbContext db = new ClinicDbContext();
if (ModelState.IsValid)
{
try
{
var user = new ApplicationUser { UserName = pv.Email, Email = pv.Email };
var result = await UserManager.CreateAsync(user, pv.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
else
{
return View(pv);
}
Patient p = new Patient();
p.FirstName = pv.FirstName;
p.LastName = pv.LastName;
p.DateOfBirth = pv.DateOfBirth;
p.Email = pv.Email;
p.PhoneNumber = pv.PhoneNumber.ToString();
p.StreetAddress = pv.StreetAddress.ToString();
p.City = pv.City;
p.State = pv.State;
p.ZipCode = pv.ZipCode;
p.UserId = db.AspNetUsers.Max(m => m.Id);
_context.Patients.Add(p);
_context.SaveChanges();
return RedirectToAction("Index", "Admin");
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
else
{
return View(pv);
}
}