SaveChanges()方法中的异常(Entity.Framework)

时间:2015-11-18 10:37:20

标签: asp.net-mvc entity-framework asp.net-mvc-4

有课程User

namespace TaskManager.Models
{
    public class User
    {
        private const int NAME_LENGTH = 200;
        private const int EMAIL_LENGTH = 100;
        private const int PASSWORD_MIN_LENGTH = 5;
        private const int PASSWORD_MAX_LENGTH = 20;

        public int Id { get; set; }

        [Required]
        [StringLength(NAME_LENGTH)]
        public string Name { get; set; }

        [Required]
        [EmailAddress]
        [StringLength(EMAIL_LENGTH)]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(PASSWORD_MAX_LENGTH, MinimumLength = PASSWORD_MIN_LENGTH)]
        public string Password { get; set; }

        public string PasswordSalt { get; set; }

        [Required]
        [DefaultValue(UserType.User)]
        public UserType Type { get; set; }

        public ICollection<Task> Tasks { get; set; }
    }

    public enum UserType
    {
        Admin = 0,
        User = 1
    }
}

我尝试使用SimpleCrypto创建自定义用户注册 这是我的方法

[HttpGet]
public ActionResult Registration()
{
    return View();
}

[HttpPost]
public ActionResult Registration(User user)
{
    if (ModelState.IsValid)
    {
        if (!IsUserExist(user.Email))
        {

            var crypto = new SimpleCrypto.PBKDF2();

            var encrpPass = crypto.Compute(user.Password);

            var newUser = _db.Users.Create();

            newUser.Name = user.Name;
            newUser.Email = user.Email;
            newUser.Type = UserType.User.ToString();

            newUser.Password = encrpPass;
            newUser.PasswordSalt = crypto.Salt;

            _db.Users.Add(newUser);
            _db.SaveChanges();

            return RedirectToAction("Index", "Home");

        }
        else
        {
            ModelState.AddModelError("", "User already exists");
        }
    }
    else
    {
        ModelState.AddModelError("", "Data is incorrect");
    }

    return View(user);
}

如果我使用此表架构,则注册正常 enter image description here

但如果我尝试将Id设为Primary Key并设置Identity == trueIdentity Increment = 1

enter image description here

我在_db.SaveChanges();方法中遇到了例外情况 我做错了什么?如何解决?

例外

System.Data.SqlServerCe.SqlCeException:无法修改列。 [列名= Id]

我试图改变模型

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

但我得到了同样的例外。

0 个答案:

没有答案