简体   繁体   中英

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. 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:

setting default values

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM