2

I am trying to read the custom attributes using reflection set by Fluent API in EntityFramework Core. I did a bit of research and found that MetadataWorkspace can be helpful as suggested in these links: Link 1, Link 2. All these solutions are on EntityFramework.

How to use metadataworkspace with EntityFramework Core?

Or, Is there any solution on Asp.Net Core 2.1 and EntityFramework Core to read the configuration properties at runtime set by Fluent API ?

dipneupane
  • 63
  • 1
  • 8

1 Answers1

2

EF core does not have MetadataWorkspace
To get the Annotations set by the EF Core Fluent API use this as an example:

    public class Basic {
        public int Id {get; set;}
        public string Value {get; set;}
    }

    public class BasicConfig {
        public void Configure(EntityTypeBuilder<Basic> builder)
        {
            builder.ToTable("Basic");

            builder.HasKey(e => e.Id)
                .HasName("PK_Basic");


            builder.Property(e => e.Value)
                .IsRequired()
                .HasMaxLength(500)
                .IsUnicode(false)
                .HasColumnName("Value");
        }
    }


    /// <summary>
    /// Returns the MaxLength of a PropertyInfo (field) off of a Custom EF modal Type
    /// </summary>

    public int DetermineSize(Type basicModelType) {
        IEntityType fake = _context.Model.FindEntityType(basicModelType);
        IProperty prop = fake.GetProperty("Value");
        IEnumerable<IAnnotation> ann = prop.GetAnnotations();

        int maxSize = (int)ann.SingleOrDefault(item => item.Name.Equals("MaxLength"))?.Value;

        return maxSize;
    }