Reputation: 87
I am using EF Core 2.1 to create a database. I am able to set the default value of a column like
public class SchoolContext : DbContext
{
....
protected override void OnModelCreating(ModelBuilder modelBuilder) {
....
modelBuilder.Entity<Student>().Property(s => s.LastLoginDateTime).HasDefaultValueSql("SYSUTCDATETIME()");
}
....
}
However, when I try to use the IEntityTypeConfiguration
to set the default value, I get the build an error message (printed in the code below). I understand that the HasDefaultValueSql()
is not available in IEntityTypeConfiguration<>
.
How can I work around with that limitation? By the way, I followed the Scott Sauber in his 'Customizing EF Core 2.0+ Entity/Table Mapping with IEntityTypeConfiguration - Sept 11, 2017) to create my SchoolContext
.
https://scottsauber.com/2017/09/11/customizing-ef-core-2-0-with-ientitytypeconfiguration/
My code:
public class StudentConfig : IEntityTypeConfiguration<Student>
{
public void Configure (EntityTypeBuilder<Student> builder)
{
....
// Error CS1061 'PropertyBuilder<DateTime>' does
// not contain a definition for 'HasDefaultValueSql'
// and no extension method 'HasDefaultValueSql'
// accepting a first argument of Type 'PropertyBuilder<DateTime>'
// could be found (are you missing a using directive
// or an assembly reference?)
// Data C:\Users\Paul\source\repos\School\Data\EFClasses
// \Configurations\StudentConfig.cs 22 Active
builder.Entity<Student>().Property(s => s.RecIn).HasDefaultValueSql("SYSUTCDATETIME()");
....
}
}
Upvotes: 2
Views: 4610
Reputation: 205629
The builder
parameter type of the Configure
method is EntityTypeBuilder<T>
, and is exactly the same returned by ModelBuilder.Entity<T>
method.
So when using IEntityTypeConfiguration<T>
, you should use builder
directly (w/o Entity<T>()
call which is for ModelBuilder
):
public class StudentConfig : IEntityTypeConfiguration<Student>
{
public void Configure(EntityTypeBuilder<Student> builder)
{
builder.Property(s => s.LastLoginDateTime).HasDefaultValueSql("SYSUTCDATETIME()");
}
}
Btw, the ModelBuilder.Entity<T>()
method has overload with Action<EntityTypeBuilder<T>
argument which can be uses in a similar fashion:
modelBuilder.Entity<Student>(builder =>
{
builder.Property(s => s.LastLoginDateTime).HasDefaultValueSql("SYSUTCDATETIME()");
});
Update: Please note that HasDefaultValueSql
is extension method defined in RelationalPropertyBuilderExtensions
class from Microsoft.EntityFrameworkCore.Relational assembly, so make sure your project is referencing it.
Upvotes: 8