0

Firstly this is just a simple feature that is supported by at least EF Core for SQL Server, but for Oracle (the provider implemented by Oracle), I'm not so sure if it's supported.

Simply I have an entity class like this:

public class Item {
    public int Id {get;set;}
    public DateTime CreatedDateUtc {get;set;}
}

The problem is how to configure the EF core to auto-generate database's date to CreatedDateUtc each time inserting without having to set that value on client side?

Here's what I've tried:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Item>()
               .Property(e => e.CreatedDateUtc)
               .ValueGeneratedOnAdd();                 
}

But after running add-migration, the generated class is just empty like this:

protected override void Up(MigrationBuilder migrationBuilder)
{

}

protected override void Down(MigrationBuilder migrationBuilder)
{

}

So actually it does nothing with that configuration (not supported?). Also the first thing is to generate a datetime value, the second important thing is to generate a UTC datetime value. I believe in the feasibility for the first requirement whereas the second seems to be unfeasible at least with Oracle EF Core? (nuget name: Oracle.EntityFrameworkCore).

I am keen to achieve the first requirement, even if the second requirement is impossible. At least we need some work-around then.

halfer
  • 19,824
  • 17
  • 99
  • 186
Hopeless
  • 4,397
  • 5
  • 37
  • 64
  • 1
    Possible duplicate of [How to automatically populate CreatedDate and ModifiedDate?](https://stackoverflow.com/questions/38183021/how-to-automatically-populate-createddate-and-modifieddate) – Jan Paolo Go Jun 19 '19 at 23:23
  • Thanks, `HasDefaultValueSql` is the way to go, it's very hidden inside that question thread (some kind of later update for EF Core). – Hopeless Jun 22 '19 at 09:17

1 Answers1

0

Try this -

protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
          modelBuilder.Entity<Item>()
               .Property(b => b.CreatedDateUtc)
               .HasDefaultValueSql("GETUTCDATE()");
    }
Mofaggol Hoshen
  • 686
  • 1
  • 7
  • 20
  • actually I had found the `.HasDefaultValueSql` from a comment to my question before. Also please note that I'm using Oracle, so the sql will be something different than "GETUTCDATE()", I had to use `sys_extract_utc(systimestamp)` instead. – Hopeless Jun 22 '19 at 09:16