【问题标题】:"The INSERT statement conflicted with the FOREIGN KEY constraint"INSERT 语句与 FOREIGN KEY 约束冲突
【发布时间】:2016-05-06 21:59:30
【问题描述】:

错误信息:

INSERT 语句与 FOREIGN KEY 约束冲突 “FK_UserProfile_UserLogin”。数据库发生冲突 “ToDoDB”,表“dbo.UserLogin”,列“UserLoginID”。该声明 已终止。

这意味着什么?

我正在尝试构建一个简单的登录和配置文件 MVC5 网络应用程序。我在 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 对象并添加并保存到数据库中。这似乎真的奏效了。但是我构建、添加和保存UserProfile 对象的下一步似乎不起作用。至少数据库没有更新。

这是处理动作的控制器:

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 还要少)。

【问题讨论】:

  • 您是否尝试在 AddUserAccount() 的第一行设置断点以确保 newUser 具有值?
  • 好的,现在它给了我一个错误:“INSERT 语句与 FOREIGN KEY 约束“FK_UserProfile_UserLogin”冲突。冲突发生在数据库“ToDoDB”、表“dbo.UserLogin”、列“UserLoginID”中. 声明已终止”这意味着什么?
  • 在第二个db.SaveChanges() 之前放一个断点,检查UP.UserLoginID 的值是否正确。
  • 用户名、密码、名字、姓氏、创建日期和电子邮件都有正确的值。 UserLogin 显示为 0。但它应该是 1 对吗?如果它是在数据库中输入的第一个项目?我将这两个表都设置为递增(1.1)主键。并且 userprofile 表将 UserLoginID 设置为外键。有什么问题?
  • 第一个db.SaveChanges()成功了吗?在第一个db.SaveChanges() 之后,你的UserLogin 表中有记录吗?

标签: c# asp.net database asp.net-mvc-5


【解决方案1】:

啊,是的,问题来了之后:

UP.UserLoginID = newUser.UserLoginID;

不是newUser,应该是:

UP.UserLoginID = UL.UserLoginID;

因为你刚刚将对象UL添加到数据库中,要获取插入对象的生成ID,你必须调用它,而不是newUser对象。

【讨论】:

  • 你太棒了。毕竟就是这样。太感谢了。数据库已完全更新,但现在我收到 HTTP 错误 401.0 - 未经授权。它不会重定向到“欢迎”视图。是因为我为“欢迎”视图添加了 [authorize] 注释吗?
  • 是的,请仔细检查您的身份验证过程:)
  • 我希望我能给你一百万个赞。现在我只需要弄清楚如何将另一个表添加到我的数据库以及与之相关的所有控件
  • 谢谢。乐于助人:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-27
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多