简体   繁体   中英

ASP.Net Core Linking Identity User To Model

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: 在此处输入图像描述

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...

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;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM