We have defined a base class as
public class BaseSchema
{
[Key]
[ScaffoldColumn(false)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public bool IsDeleted { get; set; }
public DateTime PerformedOn { get; set; }
}
Deriving all other classed form this Base schema. Sample class is
public class HoodAudit : BaseSchema{}
After adding HoodAudit in datacontext class and runing migration, migration file generated as
CreateTable(
"dbo.HoodAudits",
c => new
{
Id = c.Int(nullable: false, identity: true),
//Other properties
IsDeleted = c.Boolean(nullable: false),
PerformedOn = c.DateTime(nullable: false),
},
We want to make PerformedOn as PerformedOn = c.DateTime(nullable: false, defaultValueSql: "GETDATE()"), and IsDeleted as IsDeleted = c.Boolean(nullable: false, defaultValueSql: "0"),
Is there any way we can achieve this? As we are deriving all other classes from BaseSchema, would be great if you suggest any generic way which will apply in al its derived classes. Thank You!
As far as I know, there is no attribute to specify a default database value (SQL calculated or otherwise) on your entity property, instead you need to add the information to your "OnModelCreating" method of your DbContext class and it'll use that info for the migration. You'll find there are many powerful things you can do OnModelCreating that you can't do with attributes...
Here are two sets of examples, one for EF 6, one for EF Core.
Single entity property configuration in EF 6
To do this for ALL entities inheriting from
BaseSchemain EF 6, there are three steps:DateTimeproperties (including in base classes) you want to default toGetDate()OnModelCreating:Single Entity Example in EF Core 5:
To do this for ALL entities inheriting from
BaseSchemain EF Core 5 you can use the following inOnModelCreating: