在MVC 4中更新数据库数据

时间:2013-06-03 20:00:55

标签: asp.net asp.net-mvc database asp.net-mvc-4

请忍受我的高唱,我是Asp.NET MVC的新手,我还不太了解它。

基本上我想要做的是从输入到表单中的信息更新数据库中的表。 我有一个注册表单,其中包含多个选项:FirstNameLastNameAgeSexSecretQuestionSecretQuestionAnswer

我想将此数据插入我的UserProfile表(我使用SimpleMembershipProvider)到相应的列。 这是我在主控制器中的完整注册ActionResult:

 [HttpPost]
        [ValidateAntiForgeryToken]
        [RecaptchaControlMvc.CaptchaValidatorAttribute]
        public ActionResult Regisztracio(RegisterModel model, bool captchaValid, string captchaErrorMessage)
        {
            if (ModelState.IsValid)
            {
                if (!captchaValid)
                {
                    ModelState.AddModelError("recaptcha", captchaErrorMessage);
                    return View(model);
                }

                try
                {
                    OneMillionDb db = new OneMillionDb();
                    User user = new User();

                    var token = WebSecurity.CreateUserAndAccount(model.UserName, model.Password, null, true);
                    user.LastName = model.LastName;
                    user.FirstName = model.FirstName;
                    user.Age = model.Age;
                    user.Sex = model.Sex;
                    user.SecretQuestion = model.SecretQuestion;
                    user.SecretQuestionAnswer = model.SecretQuestionAnswer;
                    db.Users.Add(user);
                    db.SaveChanges();



                        return RedirectToAction("Index");


                }
                catch
                {
                    ModelState.AddModelError("UserName", "The username already exists.");
                    ModelState.AddModelError("Email", "The specified E-mail address already exists.");
                    ModelState.AddModelError("ConfirmEmail", "");
                    return View(model);
                }
            }
            return View(model);
        }

OneMillionDb是我的dbContext模型文件:

public class OneMillionDb : DbContext
    {
        public OneMillionDb()
            : base("DefaultConnection")
        {
        }
        public DbSet<User> Users { get; set; }
    }

User是表格定义的模型类。它看起来像这样:

[Table("UserProfile")]
    public class User
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        [Column]
        [Required]
        public string UserName { get; set; }
        [Column]
        public string FirstName { get; set; }
        [Column]
        public string LastName { get; set; }
        [Column]
        [Required]
        public int Age { get; set; }
        [Column]
        public string Sex { get; set; }
        [Column]
        [Required]
        public string SecretQuestion { get; set; }
        [Column]
        [Required]
        public string SecretQuestionAnswer { get; set; }
        [Column]
        public int MoneyIn { get; set; }
        [Column]
        public int MoneyOut { get; set; }
        [Column]
        public int TimesWon { get; set; }
    }

我以前在ASP.NET网页中工作,因为我使用UPDATE SQL语句执行此操作然后执行查询..

Edit3:这是我的注册视图:

@model OneMillion.Models.RegisterModel
@using Recaptcha;

@{
    ViewBag.Title = "Register";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <fieldset>
        <legend>Register</legend>
        <ul>
            <li>
                @Html.LabelFor(m => m.UserName)
                @Html.EditorFor(m => m.UserName)
            </li>
            <li>
                @Html.LabelFor(m => m.Email)
                @Html.EditorFor(m => m.Email)
            </li>
            <li>
                @Html.LabelFor(m => m.ConfirmEmail)
                @Html.EditorFor(m => m.ConfirmEmail)
            </li>
            <li>
                @Html.LabelFor(m => m.Password)
                @Html.PasswordFor(m => m.Password)
            </li>
            <li>
                @Html.LabelFor(m => m.ConfirmPassword)
                @Html.PasswordFor(m => m.ConfirmPassword)
            </li>
            <li>
                @Html.LabelFor(m => m.LastName)
                @Html.EditorFor(m => m.LastName)
            </li>
            <li>
                @Html.LabelFor(m => m.FirstName)
                @Html.EditorFor(m => m.FirstName)
            </li>
            <li>
                @Html.LabelFor(m => m.Age)
                @Html.EditorFor(m => m.Age)
            </li>
            <li>
                @Html.LabelFor(m => m.Sex)
                @Html.EditorFor(m => m.Sex)
            </li>
            <li>
                @Html.LabelFor(m => m.SecretQuestion)
                @Html.EditorFor(m => m.SecretQuestion)
            </li>
            <li>
                @Html.LabelFor(m => m.SecretQuestionAnswer)
                @Html.EditorFor(m => m.SecretQuestionAnswer)
            </li>
            <li>
                @Html.Raw(Html.GenerateCaptcha())
            </li>
        </ul>
        <input type="submit" value="Register" />
    </fieldset>
}

这是我的RegisterModel:

public class RegisterModel
    {
        [Required]
        [Display(Name = "Felhasználónév")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "E-mail cím")]
        public string Email { get; set; }

        [DataType(DataType.EmailAddress)]
        [Display(Name = "E-mail cím megerősítése")]
        [Compare("Email", ErrorMessage = "A két e-mail cím nem egyezik.")]
        public string ConfirmEmail { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "A jelszónak legalább {2} karakter hosszúnak kell lennie.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Jelszó")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Jelszó megerősítése")]
        [Compare("Password", ErrorMessage = "A jelszó és a jelszó megerősítése mezők nem egyeznek.")]
        public string ConfirmPassword { get; set; }

        [Display(Name= "Vezetéknév")]
        public string LastName { get; set; }

        [Display(Name= "Keresztnév")]
        public string FirstName { get; set; }

        [Display(Name= "Életkor")]
        public int Age { get; set; }

        [Display(Name="Nem")]
        public string Sex { get; set; }

        [Required]
        [Display(Name="Titkos kérdés")]
        public string SecretQuestion { get; set; }

        [Required]
        [Display(Name="Titkos kérdés válasza")]
        public string SecretQuestionAnswer { get; set; }
    }

编辑: 我的问题:

数据库无法更新。我知道这一点,因为我得到一个Exception,声明Column Age的值不能为NULL,但是填写了相应的输入。

EDIT2: 我也改变了代码以反映 SOfanatic 的答案,但我仍然得到错误。

Edit4:这是我在trycatch的Catch方面得到的例外:

Cannot insert the value NULL into column 'Age', table 'OneMillionDb.dbo.UserProfile'; column does not allow nulls. INSERT fails.

3 个答案:

答案 0 :(得分:1)

更新实体类似于添加实体,因此在您的代码中:

try {
   OneMillionDb db = new OneMillionDb();
   User user = new User();

   var token = WebSecurity.CreateUserAndAccount(model.UserName, model.Password, null, true);
   user.LastName = model.LastName;
   user.FirstName = model.FirstName;
   user.Age = model.Age;
   user.Sex = model.Sex;
   user.SecretQuestion = model.SecretQuestion;
   user.SecretQuestionAnswer = model.SecretQuestionAnswer;
   db.Users.Add(user);
   db.SaveChanges();
   return RedirectToAction("Index");
}

db.Users.Add(user)更改为db.Entry(user).State = EntityState.Modified

答案 1 :(得分:1)

User班级上,将以下内容更改为

[Column]
[Required]
public int Age { get; set; }

[Column]
public int? Age { get; set; }

您的声明正在列NOT NULL,并且始终是强制性的。

答案 2 :(得分:1)

您已在User类中将UserName定义为必填字段,但在保存时您没有为字段分配任何值。这可能会抛出EntityValidationError。