DbContext.OnModelCreating - Reading custom attribute for each DbSet

35 views Asked by At

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.
        }
    }
1

There are 1 answers

0
Guru Stron On BEST ANSWER

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

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