DbContext.OnModelCreating - 读取每个 DbSet 的自定义属性

问题描述 投票:0回答:1

我有一个 IdSeqAttribute:

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

并像这样使用它(大约 60 个类):

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

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

然后,我需要在 DbContext.OnModelCreating 上为每个 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.
        }
    }
c# entity-framework-core data-annotations dbset
1个回答
0
投票

使用

ClrType
属性:

var idSeq = entityType.ClrType.GetCustomAttribute<IdSeq>()
© www.soinside.com 2019 - 2024. All rights reserved.