0

Error message:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_UserProfile_UserLogin". The conflict occurred in database "ToDoDB", table "dbo.UserLogin", column 'UserLoginID'. The statement has been terminated.

What could this mean?

I am trying to build a simple log in and profile MVC5 web app. I created my table in SQL Express.

Firstly here is my model for the sign up page:

public class UserSignUp
{
    [Key]
    public int UserLoginID { get; set; }

    //Foregin key for the login table - First name, last name, creation date, and email
    public int UserProfileID { get; set; }

    [Required(ErrorMessage = "Username is required")]
    [Display(Name = "Username")]
    public string Username { get; set; }

    [Required(ErrorMessage = "Password is required")]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required(ErrorMessage = "First Name is required")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is required")]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime CreationDate { get; set; }

    [Required(ErrorMessage = "Valid email is required")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
}

So the UserLoginID is the primary key from the UserLogin table and the UserProfileID is the primary from the UserProfile table. I set the foreign key of the UserProfile table to UserLoginID from the UserLogin.

Here is my model for creating a new user:

public class UserProfileManager
{
    public void AddUserAccount(UserSignUp newUser)
    {
        // create database connection
        using (ToDoDBEntities db = new ToDoDBEntities())
        {
            // Collect viewmodel data
            // Here building goes by object type and not foregin key relationship
            UserLogin UL = new UserLogin();
            UL.Username = newUser.Username;
            UL.Password = newUser.Password;

            // Add the UserLogin object I just built to the database
            db.UserLogins.Add(UL);
            db.SaveChanges();

            UserProfile UP = new UserProfile();
            // establish connection to UL by establishing foreign key relationship
            UP.UserLoginID = newUser.UserLoginID;
            UP.FirstName = newUser.FirstName;
            UP.LastName = newUser.LastName;
            UP.CreationDate = newUser.CreationDate;
            UP.Email = newUser.Email;

            // Add UserProfile object to databse and save changes
            db.UserProfiles.Add(UP);
            db.SaveChanges();
        }
    }

    //Check if user is real before login is allowed
    public bool isLoginReal(string LoginName)
    {
        using (ToDoDBEntities DB = new ToDoDBEntities())
        {
            // Return the user from the DB whose login name matches the LoginName string passed in as perameter
            return DB.UserLogins.Where(o => o.Username.Equals(LoginName)).Any();
        }
    }
}

My AddUserAccount is where I think I am having issues. So I start by building the UserLogin object and adding and saving to the database. That seems to work out actually. But the next step where I build, add, and save the UserProfile object doesn't seem to work. At least the database doesn't get updated.

Here is the controller handling the actions:

public class AccountController : Controller
{
    // GET: Account
    public ActionResult Index()
    {
        return View();
    }

    #region signup methods
    // Get method for signup page
    public ActionResult SignUpPage()
    {
        return View();
    }

    // Post method for signup page - post to db
    [HttpPost]
    // Pass in the UserSign up model object to be built
    public ActionResult SignUpPage(UserSignUp USUV)
    {
        // Form is filled out and then method is entered
        if (ModelState.IsValid)
        {
            // Form is filled out and database connection is established if form is valid
            UserProfileManager UPM = new UserProfileManager();

            if (!UPM.isLoginReal(USUV.Username))
            {
                // data access . adduseraccount from entity manager (where model objects are built)
                UPM.AddUserAccount(USUV);
                FormsAuthentication.SetAuthCookie(USUV.FirstName, false);
                return RedirectToAction("Welcome", "Home");
            }
            else
            {

            }
        }
        return View();
    }
    #endregion
}

To my (noob) eye everything looks good. The SignUpPage is received, then a new UserSignUp object is passed into the Post action, and entity framework object (UserProfileManager) is built, the form is authenticated and the user gets either redirected to the Welcome view or the user gets returned to the signup view.

Any chance someone can help me figure out what I am either missing or doing wrong? I included a picture of the database design for reference (I know even less about database then MVC).

Database design

Triet Doan
  • 11,455
  • 8
  • 36
  • 69
Devon
  • 27
  • 7
  • Have you tried putting a break point on the first line of AddUserAccount() to make sure newUser has values? – Eric May 06 '16 at 22:16
  • Ok now its giving me an error: "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_UserProfile_UserLogin". The conflict occurred in database "ToDoDB", table "dbo.UserLogin", column 'UserLoginID'. The statement has been terminated" What could this mean? – Devon May 06 '16 at 23:38
  • Put a break point before the second `db.SaveChanges()` and check if the `UP.UserLoginID` has correct value. – Triet Doan May 07 '16 at 01:29
  • Username, Password, FirstName, LastName, CreationDate, and Email all have correct values. UserLogin is showing as 0. But it should be 1 right? If its the first item to be input in the DB? I have both of those tables set with incrementing (1.1) primary keys. And the userprofile table has UserLoginID set as a foreign key. What could be wrong? – Devon May 07 '16 at 01:37
  • Did the first `db.SaveChanges()` succeed? After the first `db.SaveChanges()`, is there any record in your `UserLogin` table? – Triet Doan May 07 '16 at 01:41
  • Yes it did. I have attempted to get this to work and both times the SaveChanges() for the UserLogin table worked. Just not the UserProfile – Devon May 07 '16 at 01:43
  • Check my answer please :) – Triet Doan May 07 '16 at 01:51

1 Answers1

0

Ah yes, after the problem is here:

UP.UserLoginID = newUser.UserLoginID;

It's not newUser, it should be:

UP.UserLoginID = UL.UserLoginID;

Because you just added the object UL to the database, to get the generated ID of the inserted object, you have to call it, not the newUser object.

Triet Doan
  • 11,455
  • 8
  • 36
  • 69
  • youre amazing. That was it after all. Thank you so much. The DB did fully update but now I am getting a HTTP Error 401.0 - Unauthorized. It wont redirect to the "Welcome" view. Is that because of the [authorize] annotation I have for the "Welcome" view? – Devon May 07 '16 at 01:56
  • Yes, double check your authentication process :) – Triet Doan May 07 '16 at 01:58
  • I wish I could give you a million upvotes. Now I just need to figure out how to add another table to my database and all the correlating controls with it – Devon May 07 '16 at 02:02
  • Thanks. Happy to help :D – Triet Doan May 07 '16 at 02:03