'this error occurs when i press on the create button in create post form

An unhandled exception occurred while processing the request sql exception asp.net core . SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Posts_AspNetUsers_AuthorId". The conflict occurred in database "LostKidsDb", table "dbo.AspNetUsers", column 'Id'.

Here is the Post Model

    [Key]
    public int PostId { get; set; }

    [Required]
    public string Title { get; set; }

    public string Descripition { get; set; }

    public string  Image { get; set; }

    public string Address{ get; set; }

    [Display(Name ="Category")]
    public int CategoryId{ get; set; }

    [ForeignKey("CategoryId")]
    public Category Category{ get; set; }

    [Display(Name = "Sub-Category")]
    public int SubCategoryId { get; set; }

    [ForeignKey("SubCategoryId")]
    public SubCategory SubCategory { get; set; }

    [Display(Name = "Author-Id")]
    [Required]
    public string AuthorId { get; set; }

    [ForeignKey("AuthorId")]
    public ApplicationUser ApplicationUser { get; set; }
    [Required]
    [Display(Name = "Author-Name")]
    public string AuthorName { get; set; }

    public enum PostStatus
    {
        Pending,
        Approved,
        Rejected
    }
    public PostStatus Status { get; set; }

Here is the Application user model

public class ApplicationUser:IdentityUser
{
    public string Name { get; set; }

    public string StreetAddress { get; set; }

    public string PostalCode { get; set; }
    public string Governorate { get; set; }

    public string  City { get; set; }
}

This is the create razor view page in user controller:

  <div class="col-5">
            @if (SignInManager.IsSignedIn(User))
            {
                {
                    ApplicationUser applicationUser = await UserManager.GetUserAsync(User);

                    <input readonly asp-for="Post.AuthorName" value=" @applicationUser.Name " class="form-control" />

                }
            }
            <span class="text-danger" asp-validation-for="Post.AuthorName"></span>

        </div>
    </div>


    <div class="form-group row">
        <div class="col-2">
            <label hidden asp-for="Post.AuthorId" class="col-form-label"></label>
        </div>
        <div class="col-5">
            @if (SignInManager.IsSignedIn(User))
            {
                {
                    ApplicationUser applicationUser = await UserManager.GetUserAsync(User);

                    <input type="hidden" asp-for="Post.AuthorId" value=" @applicationUser.Id " class="form-control" />

                }
            }

Here is the Create Method in Post Controller in User Area:

    [HttpGet]
    public IActionResult Create()
    {
       
        return View(PostVM);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [ActionName("Create")]
    public async Task<IActionResult> CreatePost()
    {
        //if (ModelState.IsValid)
        //{
            
            //in case the user didn't upload an image while creating a post a default image will be uploaded with the post

            string ImagePath = @" \Images\download.png";

            //uploaded images of the created post will be saved into this static file
            var files = HttpContext.Request.Form.Files;
            if (files.Count > 0)
            {
                string webroot = webHostEnvironment.WebRootPath;

                // change the name of images uploaded to avoid duplicate names so every uploaded image
                // will take the name of the date of its uploading
                string ImageName = DateTime.Now.ToFileTime().ToString() + Path.GetExtension(files[0].FileName);

                FileStream fileStream = new FileStream(Path.Combine(webroot, "Images", ImageName), FileMode.Create);
                files[0].CopyTo(fileStream);

                ImagePath = @"\Images\" + ImageName;
            //}
            PostVM.Post.Image = ImagePath;
            db.Posts.Add(PostVM.Post);
            await db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));

        }
        return View(PostVM);
    }
    


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source