'EF Core's 'HasDefaultValueSql' cannot set current datetime
I have a model for a UserProfile which contains a field for when the user is created. I would like EF Core to automatically set the value of this field to the current datetime, whenever a new row is added to the database. To achieve this, I have made the following model:
public class UserProfile
{
public UserProfile(string username, string email)
{
Username = username ?? throw new ArgumentNullException(nameof(username));
Email = email;
}
public Guid Id { get; init; } = Guid.NewGuid();
public string Username { get; init; }
public string Email { get; private set; } = "";
public DateTime Created { get; init; }
}
In the DbContext I have overridden the OnModelCreating() method and specified that the field UserProfile.Created should by default be set to the SQL value GETDATE() (I have also tried with CURRENT_TIMESTAMP).
public class UserProfileContext : DbContext
{
public UserProfileContext(DbContextOptions<UserProfileContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserProfile>().ToTable("Account");
modelBuilder.Entity<UserProfile>()
.Property(u => u.Created)
.HasDefaultValueSql("GETDATE()");
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
But when I create a new user and request it back, I just get the following response:
[
{
"id": "3a33c8ad-7581-4adc-8c91-a65d40ec008e",
"username": "string",
"email": "string",
"created": "0001-01-01T00:00:00"
}
]
I cannot look directly in the database, since I'm using EF Core InMemory. What am I missing here?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
