public class Post
{
    [Key]// defines Post_Id as primary key of this table
    public int Post_Id { get; set; }
    public string Post_Title { get; set; }
    public string Post_Content { get; set; }
    public string Post_Description { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
    
    public string? CreatedById { get; set; }
    public string? UpdatedById { get; set; }
    
    [ForeignKey("CreatedById")]
    public ApplicationUser CreatedBy { get; set; }
    
    [ForeignKey("UpdatedById")]
    public ApplicationUser UpdatedBy { get; set; }
}

i have the following Model for my Posts the idea behind it saving what user created it and who edited it (multiple people with admin rights can edit a post)

Everything runs correctly, the tables seem to be formed correctly with the foreign keys, however after creating a Scaffold Item Controller with Views and Entity Framework, in the view when i submit my form and the create method is called

public async Task<IActionResult> Create([Bind("Post_Id,Post_Title,Post_Content,Post_Description,CreatedAt,UpdatedAt,CreatedById,UpdatedById")] Post post)
        {
            if (ModelState.IsValid)
            {
                _context.Add(post);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["CreatedById"] = new SelectList(_context.ApplicationUsers, "Id", "Id", post.CreatedById);
            ViewData["UpdatedById"] = new SelectList(_context.ApplicationUsers, "Id", "Id", post.UpdatedById);
            return View(post);
        }

the ModelState.IsValid always fails because the post.CreatedBy and post.UpdatedBy are NULL. are the relations between the tables not formed correctly or do I need to implement some logic to grab those values and set them manually?

If i remove the ModelState verification the program runs fine and I'm able to create a new post on the db (i also went and tried to manually change the field in the database itself and it says im conflicting with the FK) meaning the FK is formed correctly. I also tried using the [BindNever] on these 2 attributes but they keep showing up on the bind

0

There are 0 answers