0

I am using ASP.NET Core 6 to make a simple Blog website.

I have the 2 following classes:

AppUser.cs

public class AppUser : IdentityUser
{
    public ICollection<Blog>? Blogs { get; set; }
    public string? Name { get; set; }
}

Blog.cs

public class Blog
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string UserID { get; set; }
        
    }
}

Below is suppose to get the current users info when creating a blog:

public async Task<IActionResult> OnPostAsync()
    {
        var user = await _userManager.GetUserAsync(User);

        Blog.UserID = user.Id;
        
        if (!ModelState.IsValid)
        {
            return Page();
        }

        
        _context.Blog.Add(Blog);
        
        await _context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }

For some reason, the ModelState is not valid when attempting to create the new Blog. When I print to console the Blog.UserID and Blog.Title I get the correct data, but it still does not work.

Potentially unrelated, but the table Entity Framework made for the Blog is: enter image description here

Which I also don't understand why there is a UserID and AppUserId column.

Any help would be greatly appreciated!

Update

I seem to have fixed it by making the UserID a nullable field.. I'm not sure if that is ideal...

Kyle
  • 13
  • 4
  • Does this model was created autometically while you have executed the `Migration command`? If so, there are couple of workaround you could implement, either you could ommit `appUserId` from the column. Moreover, you could even add the `appUserId` on your `Blog` model. I think both will allow you to resolve the issue. – Md Farid Uddin Kiron Oct 03 '22 at 07:32

1 Answers1

0

First, for your ModelState problem. I recommend you to check this ModelState.IsValid.Question

And another problem is "Which I also don't understand why there is a UserID and AppUserId column."

I think you would like to use Navigation Property.

So you should change your entities like;

public class AppUser : IdentityUser
{
   public string Name { get; set; }
   public ICollection<Blog> Blogs { get; set; }
}

public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string AppUserId { get; set; }
    public AppUser AppUser {get;set;}
}
serhatyt
  • 180
  • 2
  • 14