2016-05-06 214 views
0

錯誤消息:「INSERT語句衝突與外鍵約束

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.

這到底意味着什麼

我試圖建立和配置文件MVC5 web應用程序我創建了一個簡單的日誌我的? 。表中的SQL Express

首先,這裏是我的註冊頁面模型:

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

因此,UserLoginIDUserLogin表中的主鍵,而UserProfileIDUserProfile表中的主鍵。我將UserProfile表的外鍵從UserLogin設置爲UserLoginID

這裏是我創建新用戶模型:

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

AddUserAccount是我覺得我有問題。因此,我首先構建UserLogin對象並添加並保存到數據庫。這似乎實際上解決了。但是下一步,我構建,添加和保存對象似乎不起作用。至少數據庫不會更新。

這裏是控制器處理操作:

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 
} 

要我(小白)眼睛一切正常。收到SignUpPage,然後新的UserSignUp對象被傳遞到Post操作中,並且實體框架對象(UserProfileManager)被構建,表單被認證並且用戶被重定向到Welcome視圖,或者用戶被返回到註冊視圖。

有人可以幫助我找出我要麼失蹤或做錯的機會嗎?我包括了一個數據庫設計的參考圖片(我對數據庫和MVC的瞭解甚少)。

Database design

+0

您是否嘗試在AddUserAccount()的第一行放置一個斷點以確保newUser具有值? – Eric

+0

現在好了,它給了我一個錯誤:「INSERT語句與FOREIGN KEY約束」FK_UserProfile_UserLogin「衝突。數據庫」ToDoDB「,表」dbo.UserLogin「,」UserLoginID「列發生衝突。 語句已終止「這是什麼意思? – Devon

+0

在第二個'db.SaveChanges()'之前放置一個斷點,並檢查'​​UP.UserLoginID'是否具有正確的值。 – AnhTriet

回答

0

是啊,以後的問題就在這裏:

UP.UserLoginID = newUser.UserLoginID; 

這不是newUser,它應該是:

UP.UserLoginID = UL.UserLoginID; 

因爲你剛纔添加的對象UL到數據庫,要獲取插入對象的生成ID,您必須調用它,而不是newUser對象。

+0

你真了不起。畢竟這是它。非常感謝。數據庫完全更新,但現在我得到一個HTTP錯誤401.0 - 未經授權。它不會重定向到「歡迎」視圖。這是因爲我對「歡迎」視圖有[authorize]註釋嗎? – Devon

+0

是的,仔細檢查你的身份驗證過程:) – AnhTriet

+0

我希望我能給你100萬upvotes。現在我只需要弄清楚如何添加另一個表到我的數據庫和所有與它相關的控件 – Devon

相關問題