Pau*_*aul 1 c# entity-framework entity-framework-core
我正在使用 EF Core 2.1 创建数据库。我可以设置列的默认值,例如
public class SchoolContext : DbContext
{
....
protected override void OnModelCreating(ModelBuilder modelBuilder) {
....
modelBuilder.Entity<Student>().Property(s => s.LastLoginDateTime).HasDefaultValueSql("SYSUTCDATETIME()");
}
....
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用IEntityTypeConfiguration来设置默认值时,我收到构建错误消息(打印在下面的代码中)。据我所知,HasDefaultValueSql()不在可用IEntityTypeConfiguration<>。
我该如何解决这个限制?顺便说一句,我跟随 Scott Sauber 在他的“使用 IEntityTypeConfiguration 自定义 EF Core 2.0+ 实体/表映射 - 2017 年 9 月 11 日”中创建了我的SchoolContext.
https://scottsauber.com/2017/09/11/customizing-ef-core-2-0-with-ientitytypeconfiguration/
我的代码:
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()");
....
}
}
Run Code Online (Sandbox Code Playgroud)
方法的builder参数类型Configure是EntityTypeBuilder<T>,和ModelBuilder.Entity<T>方法返回的完全一样。
因此,在使用 时IEntityTypeConfiguration<T>,您应该builder直接使用(无需Entity<T>()调用 for ModelBuilder):
public class StudentConfig : IEntityTypeConfiguration<Student>
{
public void Configure(EntityTypeBuilder<Student> builder)
{
builder.Property(s => s.LastLoginDateTime).HasDefaultValueSql("SYSUTCDATETIME()");
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,该ModelBuilder.Entity<T>()方法具有带Action<EntityTypeBuilder<T>参数的重载,可以以类似的方式使用:
modelBuilder.Entity<Student>(builder =>
{
builder.Property(s => s.LastLoginDateTime).HasDefaultValueSql("SYSUTCDATETIME()");
});
Run Code Online (Sandbox Code Playgroud)
更新:请注意,这HasDefaultValueSql是在Microsoft.EntityFrameworkCore.Relational程序集的RelationalPropertyBuilderExtensions类中定义的扩展方法,因此请确保您的项目正在引用它。
| 归档时间: |
|
| 查看次数: |
2122 次 |
| 最近记录: |