I am using Entity Framework Core and created one-to-many relationship between 2 tables:
public class Fgf
{
public int FgfID { get; set; }
public string FGFName { get; set; }
...
public ICollection<ApplicationUser> ApplicationUsers { get; set; }
}
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
...
}
In this case EFCore is adding automatically FgfID column in ApplicationUser, but I cannot access it in the controller.
I am trying to add the FgfID in the ApplicationUser
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
...
public int FgfID { get; set; }
public Fgf Fgf { get; set; }
}
I have a form, where I create an FGF and assign to him a user with a selectlist. I am using a simple form with POST action. I am not using model for the form as I have another form on this Razor Page.
In the controller I have:
[HttpPost]
public async Task<IActionResult> NewFgf(string FGFName, string ApplicationUser)
{
if (ModelState.IsValid) {
var fgf = new Fgf
{
FGFName = FGFName,
};
var usertoupdate = await _context.Users
.Where(c=> c.Id == ApplicationUser)
.SingleOrDefaultAsync();
usertoupdate.FgfID = fgf.FgfID;
_context.Users.Update(usertoupdate);
_context.Add(fgf);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View();
}
The error I get is:
SqlException: The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_AspNetUsers_Fgf_FgfID". The conflict occurred in database "aspnet-StreamPixelVer2-3E2C2112-15B8-48A4-8619-4773C5ADBFBD", table "dbo.Fgf", column 'FgfID'. The statement has been terminated.
What am I doing wrong? What is the best practice to save the data to the DB with Many-To-One, One-To-Many relationship with the Asp.net Core?
Since you don't have fgf.FgfID, try this:
using Microsoft.EntityFrameworkCore.ChangeTracking;
.....
....
var usertoupdate = await _context.Set<ApplicationUser>()
.Where(c=> c.Id == applicationUser.Id)
.SingleOrDefaultAsync();
var fgf = new Fgf
{
FGFName = FGFName,
};
fgf.ApplicationUsers = new ObservableCollectionListSource<ApplicationUser>();
fgf.ApplicationUsers.Add(usertoupdate);
_context.Set<Fgf>().Add(fgf);
await _context.SaveChangesAsync();