0
votes

I have column, columnA, and columnB models. I am trying to override the" protected override void OnModelCreating(ModelBuilder modelBuilder)" method and trying to implement backing fields.

public class Column<TKey> : AuditableModel<TKey>
    where TKey: IComparable
{
    public string Name { get; set; }
    [Required]
    public Settings Settings {get;,set;} = new Settings();
}

public class ColumnA : Column<Guid>
{
    public Guid Id { get; set; }
}
public class ColumnB : Column<Guid>
{
    public Guid Id { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
    { 
        modelBuilder.Entity<ColumnA>()
            .Property(x => x.Settings)

        modelBuilder.Entity<ColumnB>()
            .Property(x => x.Settings)

}

How can I use a "Column" type for backing fields instead of doing this separately for a ColumnA and columnB (on a modelCreating method)?

1
Maybe look at IEntityTypeConfiguration<T> classes, and then register them in OnModelCreating(...) with modelBuilder.ApplyConfigurationsFromAssembly(assembly);. - Gup3rSuR4c
@Gup3rSuR4c Would you please give me an example on how to implement that? - Osheca

1 Answers

1
votes

Here's how I do it with my EF projects. This is with a simple example of a Car model, adapt it to fit your needs.

public class Car {
    public int Id { get; set; }
    public string Name { get; set; }
}

internal sealed class CarConfiguration :
    IEntityTypeConfiguration<Car> {
    public void Configure(
        EntityTypeBuilder<Car> builder) {
        builder.ToTable("Cars").HasKey(
            t => t.Id);

        builder.Property(
            p => p.Name).HasMaxLength(255).IsRequired();
    }
}

public class MyContext :
    DbContext {
    protected override void OnModelCreating(
        ModelBuilder modelBuilder) {
        var assembly = typeof(MyContext).Assembly;

        modelBuilder.ApplyConfigurationsFromAssembly(assembly);
    }
}

You can read up more on it here.