I have been struggling with foreign key things in my project but to make my point clear, I am going to give you the official tutorial for the relationship things in ASP.NET.
I have created these two models in this page.
// Principal (parent)
public class Blog
{
public int Id { get; set; }
public ICollection<Post> Posts { get; } = new List<Post>(); // Collection navigation containing dependents
}
// Dependent (child)
public class Post
{
public int Id { get; set; }
public int BlogId { get; set; } // Required foreign key property
public Blog Blog { get; set; } = null!; // Required reference navigation to principal
}
They are our models. After creating these models in Models folder, I have created their corresponding controllers. Then, I have added this to my Context script in Data folder:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasMany(e => e.Posts)
.WithOne(e => e.Blog)
.HasForeignKey(e => e.BlogId)
.IsRequired();
}
Finally, I have typed add-migration and update-database, everything worked fine. Then I have created a Blog in /Blogs/Create. It is successfully done. But when I tried to add a new Post, I have got nothing, the page is just reloaded with nothing done.I have added some breakpoints to the create function in PostsController and saw that ModelState is invalid.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,BlogId")] Post post)
{
if (ModelState.IsValid)
{
_context.Add(post);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["BlogId"] = new SelectList(_context.Set<Blog>(), "Id", "Id", post.BlogId);
return View(post);
}
ModelState remains still invalid. It makes sense since we are not pushing anything to this function as a parameter from the Create.cshtml. But I don’t get how I should handle this problem.
I am using .Net 8.
When I delete the ModelState check, I got no error. But I don’t know if this is a solid solution.