我正在使用实体框架6和代码优先方法。我有3个模型类 用户,国家和城市。我正在尝试将用户添加到数据库但无法执行此操作。 这是我的用户类。
public class User
{
public int userId { get; set; }
public int cityId { get; set; }
public String firstName { get; set; }
public String lastName { get; set; }
public String gender { get; set; }
public String email { get; set; }
public String password { get; set; }
public String photo { get; set; }
public DateTime joinDate { get; set; }
//public City city { get; set; }
//public Country country { get; set; }
public virtual City city { get; set; }
private String FullName
{
get { return firstName + lastName; }
}
}
控制器方法
[HttpPost]
public ActionResult Register(User user)
{
User reg = new User() {
cityId = 2,
firstName = "U",
lastName = "v",
email = "u33@gmail.com",
password = "123",
gender = "Male",
photo = "asd",
};
try
{
db.Users.Add(reg);
db.SaveChanges();
// TODO: Add insert logic here
return View("Index","Home");
}
catch
{
return RedirectToAction("Index", "Home");
// return View("Register", user);
}
// return View("Register", user);
}
它转到catch语句,不会添加到数据库中。
Catch Error
Exception:Thrown: "An error occurred while updating the entries. See the inner exception for details." (System.Data.Entity.Core.UpdateException)
A System.Data.Entity.Core.UpdateException was thrown: "An error occurred while updating the entries. See the inner exception for details."
Time: 10/21/2015 5:25:41 PM
Thread:Worker Thread[5576]
答案 0 :(得分:1)
由于DateTime
是值类型,因此您需要使用Nullable<DateTime>
(或DateTime?
),因为DateTime.MinValue
(默认值为{1}} a DateTime)不在许多Sql DB DateTime字段的可接受值范围内。
修复:
public class User
{
public int userId { get; set; }
public int cityId { get; set; }
public String firstName { get; set; }
public String lastName { get; set; }
public String gender { get; set; }
public String email { get; set; }
public String password { get; set; }
public String photo { get; set; }
public DateTime? joinDate { get; set; }
//public City city { get; set; }
//public Country country { get; set; }
public virtual City city { get; set; }
private String FullName
{
get { return firstName + lastName; }
}
}
第二个解决方案是在您创建joinDate
Person
分配值