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 = "Anonymous@Anonymous.com",
PasswordHash = password,
PhoneNumber = "12345678911",
Email = "Anonymous@Anonymous.com"
});
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."