我正在尝试使用带有代码优先方法的Entity Framework为最后一个日期(DateAdded)属性设置默认值。这是我的代码:
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; }
}
}
答案 0 :(得分:4)
你可以在构造函数中设置它:
public class UserProfile()
{
DateAdded = DateTime.Now;
}
答案 1 :(得分:1)
答案 2 :(得分:0)
我最终在回发时设置了这个,就像这样:
// 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);
}