[英]How do I set a default date using code first entity framework
I am trying to set a default value for the last date (DateAdded) property using Entity Framework with code first methods. 我正在尝试使用带有代码优先方法的Entity Framework为最后一个日期(DateAdded)属性设置默认值。 Here is my code:
这是我的代码:
namespace BackOffice.Models
{
public class UsersContext : DbContext
{
public UsersContext()
//: base("DefaultConnection")
: base("ProofPixDB")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
//public DateTime DOB { get; set; }
[DataType(DataType.Date)]
public DateTime? DOB { get; set; } //This allows null
[Required]
[DataType(DataType.Date)]
public DateTime DateAdded { get; set; }
}
}
You could set it up in the constructor: 您可以在构造函数中进行设置:
public class UserProfile()
{
DateAdded = DateTime.Now;
}
i used to handle this like in te following link: 我以前在以下链接中处理过此问题:
basically using a "factory" with reflection. 基本上使用带有反射的“工厂”。
I ended up setting this on postback, like so: 我最终将其设置为回发,如下所示:
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
DateTime rightNow = DateTime.Now;
//WebSecurity.CreateUserAndAccount(model.UserName, model.Password); //too limited used CreateUserAndAccount method below
var extendedUserProperties = new { SubscriberId = subscriber.SubscriberId, Email = model.Email, DateAdded = rightNow };
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, extendedUserProperties);
Roles.AddUserToRole(model.UserName, Request.Form["RoleName"]);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.