“INSERT语句与FOREIGN KEY约束冲突

时间:2016-05-06 21:59:30

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

错误讯息:

  

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表的外键设置为UserLoginID中的UserLogin

以下是我创建新用户的模型:

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
}

对于我的(noob)眼睛,一切看起来都很好。收到SignUpPage,然后将新的UserSignUp对象传递到Post操作,并构建实体框架对象(UserProfileManager),对表单进行身份验证并确认用户获取重定向到Welcome视图或用户返回到注册视图。

有人可以帮助我找出我错过或做错的事吗?我提供了一张数据库设计图片供参考(我对数据库的了解甚至更少,然后是MVC)。

Database design

1 个答案:

答案 0 :(得分:0)

啊,是的,问题出现后:

UP.UserLoginID = newUser.UserLoginID;

不是newUser,应该是:

UP.UserLoginID = UL.UserLoginID;

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