繁体   English   中英

“ INSERT语句与FOREIGN KEY约束冲突

[英]"The INSERT statement conflicted with the FOREIGN KEY constraint

错误信息:

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

这意味着什么?

我正在尝试构建一个简单的登录并配置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表中的主键。 我设置的外键UserProfileUserLoginIDUserLogin

这是我创建新用户的模型:

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视图或将用户返回到Signup视图。

有人可以帮助我弄清楚我所缺少或做错了什么吗? 我附上了数据库设计的图片以供参考(我对数据库的了解甚于MVC)。

数据库设计

是的,问题出在这里之后:

UP.UserLoginID = newUser.UserLoginID;

它不是newUser ,应该是:

UP.UserLoginID = UL.UserLoginID;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM