0

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.
        }
    }
2
  • Does this answer your question? How do I read an attribute on a class at runtime? Commented Dec 26, 2023 at 15:00
  • 1
    entityType.ClrType is your class type. Get attributes using standard technique. GetAnnotations() is not proper way, it is more EF Core API specific. Commented Dec 26, 2023 at 15:02

1 Answer 1

1

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

var idSeq = entityType.ClrType.GetCustomAttribute<IdSeq>()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.