Search code examples
c#entity-framework-coredata-annotationsdbset

DbContext.OnModelCreating - Reading custom attribute for each DbSet


I have a IdSeqAttribute:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class IdSeq(string seq) : Attribute
{
    public string Seq = seq;
}

and use it like this (about 60 classes):

[IdSeq("Customer")]
public class Customer : MyModel
{
    public string Nome { get; set; } = "";
}

[IdSeq("Product")]
public class Product : MyModel
{
    public string Nome { get; set; } = "";
}

Then, I need to get this attibute on DbContext.OnModelCreating, for each DbSet<>:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    
        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        {
            var annotatios = entityType.GetAnnotations();
            // here, I can see two attributes, but "IdSeq" isn't one of them.
        }
    }

Solution

  • Use the IReadOnlyTypeBase.ClrType property to get the entity type and get custom attributes from it:

    var idSeq = entityType.ClrType.GetCustomAttribute<IdSeq>()