我有很多类,如下所示:
public class ModelOneConfiguration
{
public ModelOneConfiguration(EntityTypeBuilder<ModelOne> entity)
{
entity.Property(e => e.Id).IsRequired().HasDefaultValueSql("NEWID()");
entity.Property(e => e.CreatedAt).HasDefaultValueSql("getutcdate()").ValueGeneratedOnAdd();
entity.Property(e => e.UpdatedAt).HasDefaultValueSql("getutcdate()").ValueGeneratedOnUpdate();
entity.Property(e => e.FirstName).IsRequired();
entity.Property(e => e.LastName).IsRequired();
entity.Property(e => e.Email).IsRequired();
}
}
并从Db上下文类中调用它:
protected override void OnModelCreating(ModelBuilder builder)
{
new ModelOneConfiguration(builder.Entity<ModelOne>());
….other classes as well…
base.OnModelCreating(builder);
}
当我迁移时,它可以很好地显示以下结果:
Id = table.Column<Guid>(nullable: false, defaultValueSql: "NEWID()"),
CreatedAt = table.Column<DateTimeOffset>(nullable: false, defaultValueSql: "getutcdate()"),
UpdatedAt = table.Column<DateTimeOffset>(nullable: true, defaultValueSql: "getutcdate()"),
FirstName = table.Column<string>(nullable: false),
LastName = table.Column<string>(nullable: false),
Email = table.Column<string>(nullable: false)
到目前为止,一切都很好。
现在,我尝试在基类中包装Id,CreatedAt和UpdatedAt,以便可以将其与所有其他模型配置类一起使用。因此,我所做的是,我遵循了由伊万·斯托耶夫(Ivan Stoev)回答的example。
所以对于我的基类,我确实遵循了
public class BaseConfiguration<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : BaseEntities
{
public virtual void Configure(EntityTypeBuilder<TEntity> entity)
{
entity.Property(e => e.Id).IsRequired().HasDefaultValueSql("NEWID()");
entity.Property(e => e.CreatedAt).HasDefaultValueSql("getutcdate()").ValueGeneratedOnAdd();
entity.Property(e => e.UpdatedAt).HasDefaultValueSql("getutcdate()").ValueGeneratedOnUpdate();
}
}
然后我扩展了模型配置类:
public class ModelOneConfiguration : BaseConfiguration<ModelOne>
{
public ModelOneConfiguration(EntityTypeBuilder<ModelOne> entity)
{
entity.Property(e => e.FirstName).IsRequired();
entity.Property(e => e.LastName).IsRequired();
entity.Property(e => e.Email).IsRequired();
}
}
现在,当我运行迁移时,它会生成以下内容
Id = table.Column<Guid>(nullable: false),
CreatedAt = table.Column<DateTimeOffset>(nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(nullable: true),
FirstName = table.Column<string>(nullable: false),
LastName = table.Column<string>(nullable: false),
Email = table.Column<string>(nullable: false)
我们可以看到,defaultValueSql: "NEWID()"
,defaultValueSql: "getutcdate()"
和Id
中仅缺少CreatedAt
,UpdatedAt
。
我将Core 2.2与EF core 2.2一起使用。
我的问题很简单:
我在做什么错,如何解决?
答案 0 :(得分:3)
您的派生类应该在Configure
方法内部而不是在构造函数中进行工作。为此添加一个override
,并确保调用基本的Configure
方法:
public class ModelOneConfiguration : BaseConfiguration<ModelOne>
{
public override void Configure(EntityTypeBuilder<ModelOne> builder)
{
base.Configure(builder);
entity.Property(e => e.FirstName).IsRequired();
entity.Property(e => e.LastName).IsRequired();
entity.Property(e => e.Email).IsRequired();
}
}