c# – 如何处理System.Data.Entity.Validation.DbEntityValidationException?

前端之家收集整理的这篇文章主要介绍了c# – 如何处理System.Data.Entity.Validation.DbEntityValidationException?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的应用程序出现以下错误

An exception of type
‘System.Data.Entity.Validation.DbEntityValidationException’ occurred
in EntityFramework.dll but was not handled in user code

Additional information: Validation Failed for one or more entities.
See ‘EntityValidationErrors’ property for more details.

尝试注册新用户时收到此错误. ‘db.SaveChanges()’发生错误

这是代码

public ActionResult Registration(x.Models.User user)
        {
            if(ModelState.IsValid)
            {
                using(var db = new xDBEntities1())
                {
                    var crypto = new SimpleCrypto.PBKDF2();
                    var encrpPass = crypto.Compute(user.password);
                    var sysUser = db.users.Create();

                    sysUser.email = user.email;
                    sysUser.username = user.username;
                    sysUser.password = encrpPass;
                    sysUser.premium_credits = 0;
                    sysUser.login_times = 0;
                    sysUser.last_ip = Request.ServerVariables["REMOTE_ADDR"];
                    sysUser.creation_ip = Request.ServerVariables["REMOTE_ADDR"];
                    sysUser.banned = 0;
                    sysUser.creation_date = DateTime.Now;
                    sysUser.creation_time = DateTime.Now.TimeOfDay;

                    db.users.Add(sysUser);
                    db.SaveChanges();
                }
            }
            return RedirectToAction("Index","Home");
        }

编辑:
用户模型类

public class User
    {
        [required]
        [StringLength(50)]
        [Display(Name="Username: ")]
        public String username { get; set; }
        [required]
        [DataType(DataType.Password)]
        [StringLength(50,MinimumLength=6)]
        [Display(Name="Password: ")]
        public string password { get; set; }
        [required]
        [EmailAddress]
        [StringLength(50)]
        public string email { get; set; }
        public int phonenumber { get; set; }
        public int mobilephonenumber { get; set; }

    }
}

我该怎么处理?

解决方法

有一些数据库验证发生,阻止您将数据写入其中.

解决方案已在本页面上说明:

Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details

作为您使用.net mvc的额外注意事项,您应该使用System.Diagnostics.Debug.WriteLine()而不是Console.Writeline(),并且在调试时将写入调试输出窗口.由于在运行mvc项目时无法写入控制台.

原文链接:/csharp/97232.html

猜你在找的C#相关文章