Template to add in most Classes to create Migration Models with EF Core
With DataAnnotations there is one point at Base Class to declare using Attributes for example ...TypeName...
Every Model which inherits from that BaseClass is scaffolded correct and all Attributes are taken
With FluentAPI you have to declare Property attributes for example ...HasColumnTypes... on each Model you want to create. Or loop through after ModelBuilder is finished or create a Convention for ModelFinalizer
Every Model inherited from BaseClass has to be modified manually/looped for each property, regardless of defining a Grouped SetupClass for that BaseClass
How to use FluentAPI to get same results as DataAnnotation with a single Point of Definition ?
expected result
CREATE DATABASE [BlogsMS];
CREATE TABLE [LogEntries] (
[Id] int NOT NULL IDENTITY,
[CreatedAt] smalldatetime NOT NULL, -- from DataAnnotations
[UpdatedAt] smalldatetime NOT NULL, -- from FluentAPI with SingleConfigPoint ?
);
Source
template class
public abstract class DefaultAuditColumns
{
[Column(TypeName = ("smalldatetime"))]
public DateTime CreatedAt { get; set; } // DB Type defined with DataAnnotations
public DateTime UpdatedAt { get; set; } // DB Type defined FluentAPI Grouped OnModelCreating
}
first example class/entity
public class TableLogged : DefaultAuditColumns
{
public int Id { get; set; }
public string? Description { get; set; }
}
second example class/entity
public class AnotherTableLogged : DefaultAuditColumns
{
public int Id { get; set; }
public string? Description { get; set; }
}
Sql table results
CREATE DATABASE [BlogsMS];
CREATE TABLE [AnotherLogEntries] (
[Id] int NOT NULL IDENTITY,
[Description] nvarchar(200) NULL,
[CreatedAt] smalldatetime NOT NULL,
[UpdatedAt] datetime2 NOT NULL,
CONSTRAINT [PK_AnotherLogEntries] PRIMARY KEY ([Id])
);
CREATE TABLE [LogEntries] (
[Id] int NOT NULL IDENTITY,
[Description] nvarchar(200) NULL,
[CreatedAt] smalldatetime NOT NULL,
[UpdatedAt] datetime2 NOT NULL,
CONSTRAINT [PK_LogEntries] PRIMARY KEY ([Id])
);
How to use FluentAPI to get same results as DataAnnotation with a single Point of Definition ?
The Suggestion Entity Framework Core 2.0: How to configure abstract base class once Ivan Stoev – grek40 does the job but
Some of the Property Attributes then still are missing in scaffolded Model/Classes.
The Modified Class look now like, all works as expected :-)
public class TableLoggedConfiguration : DefaultAuditColumnsConfiguration<TableLogged>, IEntityTypeConfiguration<TableLogged>
{
public void Configure(EntityTypeBuilder<TableLogged> entity)
{
base.Configure(entity); // <--
// entity.Property(e => e.ReviewedAt).HasColumnType("smalldatetime");
// entity.Property(e => e.CreatedBy).HasMaxLength(30);
// entity.Property(e => e.UpdatedBy).HasMaxLength(30);
entity.Property(e => e.DecimalType).HasColumnType("decimal(18,5)").HasPrecision(18, 5);
}
}