2016-05-06 98 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

相关问题