Niranjan godbole
Niranjan godbole

Reputation: 903

By default how to insert created date each time when new record is inserted into database in mvc 4 entity framework

Whenever I tried to insert data into database i am not able to get current date and in view I am hiding that particular field. Now whenever i insert some data to database created date should automatically inserted.

This is my savechanges method.

public override int SaveChanges()
 {
  var entities = ChangeTracker.Entries()
   .Where(x => x.Entity is DocumentMaster &&
   (x.State == EntityState.Added || x.State == System.Data.EntityState.Modified));

   var currentUsername = "Anonymous";
   foreach (var entity in entities)
    {
     if (entity.State == EntityState.Added)
      {
       ((DocumentMaster)entity.Entity).CreatedDate = DateTime.Now;
       ((DocumentMaster)entity.Entity).CreatedBy = currentUsername;
      }
    }
     return base.SaveChanges();
    }
  }

This is my interface.

interface DocumentMaster
    {
        string CreatedBy { get; set; }
        DateTime CreatedDate { get; set; }
    }

And this is my class

public partial class ts_upld_doc
    {
        public ts_upld_doc()
        {
            this.tr_upld_content = new HashSet<tr_upld_content>();
        }

        public int upld_docid { get; set; }
        public int usr_createdby { get; set; }
    public Nullable<System.DateTime> upld_createddate { get; set; }
}

Do i need ti implement interface in class? I tried to implement but It did not work. Can anyone suggest me on this?

Upvotes: 1

Views: 3216

Answers (2)

Chetan Pangam
Chetan Pangam

Reputation: 370

Above Solution is good and works fine but If you update the same record then date get modified with latest date and time. I got simple solution. In create view, write below code:

 @Html.HiddenFor(model => model.EntryDateTimeStamp, Model.EntryDateTimeStamp = DateTime.Now) 

and In controller, just pass new object:

public ActionResult Create()
        {
            return View(new MaterialType());
        }

to avoid date modification in edit view:

  @Html.HiddenFor(model => model.EntryDateTimeStamp, Model.EntryDateTimeStamp = Model.EntryDateTimeStamp)

There is no need of Override any Method.

Upvotes: 0

Georg Patscheider
Georg Patscheider

Reputation: 9463

To elaborate on the "Set automatically in the database" solution:

Set up the CreationDate property in the entity model class:

public class MyPersistableEntity {

    public MyPersistableEntity() {
        // initialize in ctor so behaviour is the same for freshly created and loaded entities
        CreationDate = DateTime.Now;
    }

    [Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime CreationDate { get; set; }
}

Tell SQL Server to use default value for this column in your entity migration:

public partial class UseUtcDateAsDefault : DbMigration {
    public override void Up() {
        // auto generated date for CreationDate
         AlterColumn("dbo.MyPersistableEntity ", "CreationDate", 
             c => c.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()"));
    }
}

Upvotes: 1

Related Questions