Search code examples
c#asp.netasp.net-identity

The INSERT statement conflicted with the FOREIGN KEY with user Id (ASP Identity)


I'm working on a feature that allows a user to submit a post via a form, it successfully obtains the user Id from AspNetUsers. I have implemented a radio button that gives a user the option to become an anonymous submission. The code is as follows,

protected void AddPost(object sender, EventArgs e)
{



    var User = System.Web.HttpContext.Current.User.Identity.GetUserId();
    if (Convert.ToBoolean(Int32.Parse(inputAnonymous.SelectedValue)))
    {
        User = "anonymous";
    }

    Post newPost = new Post()
    {
        postTitle = inputTitle.Text,
        postBody = inputBody.Text,
        postDescription = inputDescription.Text,
        postCategory = inputCategory.SelectedValue,
        postAnonymous = Convert.ToBoolean(Int32.Parse(inputAnonymous.SelectedValue)),
        Id = User
    };

    using (var _dbContext = new ApplicationDbContext())
    {
        _dbContext.Posts.Add(newPost);
        _dbContext.SaveChanges();
    }
}

When the option "No" is selected for user anonymousity, the post is submitted normally, and it posts the id into the database etc, but when I click on "Yes" as I follow the debugger, it says that it is recognizing that it is anonymous, and that it should change the userId to the string "anonymous" and submit that to as the Id in the database, but I keep getting this error that prevents me that is as follows

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Posts_dbo.AspNetUsers_Id". The conflict occurred in database "aspnet-WebEnterprise-20190201040107", table "dbo.AspNetUsers", column 'Id'. The statement has been terminated.

UPDATE: I've added this bit of code to my configuration.cs

 {
                var passwordHash = new PasswordHasher();
                string password = passwordHash.HashPassword("Anonymous@123");
                context.Users.AddOrUpdate(u => u.UserName,
                    new ApplicationUser
                    {
                        UserName = "[email protected]",
                        PasswordHash = password,
                        PhoneNumber = "12345678911",
                        Email = "[email protected]"
                    });
                context.Roles.AddOrUpdate(
                    new IdentityRole { Id = "a1f04ba5-5600-4a6e-be43-ae0d6360c0ab", Name = "Anonymous" }
                    );
            }

but when I update-database on the nuget packet manager, I get the following error

"An error occurred while updating the entries. See the inner exception for details."


Solution

  • There is no user with ID "anonymous" and you get an error because of that. The AspNetUsers doesn't contain any user whose ID is "anonymous". There's nothing wrong with this code, apart from using an Id value that doesn't exist.

    As far as that problem goes, my suggestion is to create an Anonymous user, get his ID and bind that ID to all posts that should be anonymous. All anonymous post would then have the same ID, but that should not matter because they are anonymous anyway. Check this and this link for more info how to insert users via code-first architecture