Is there any way at runtime/programmatically to update the [Display(Name = "...")] display attribute?

Graeme Smith 1 Reputation point

I have a database with a large number of tables that I have imported into a .net 6 project using scaffolding (database-first). So all of the tables have been created as C# classes with no attributes decorating them, but separate code automatically created in the Context.cs file that uses Fluent Api to programmatically add the various attributes associated with the database itself.

The one thing that is not added is [Display(Name = "...)"]. In the majority of cases the display name would just be a simple regex of the column name "[a-z][A-Z]" -> "[a-z] [A-Z]", ie adding a space before each capitalized letter. Ie. a column name of "FirstName" would have a display name of "First Name". This should be fairly easy to automate, but I can't find any way to update the DisplayAttributes. The Fluent API only deals with the actual database interactions. I can get an array of the DisplayAttributes with (DisplayAttribute[])Property.GetCustomAttributes(typeof(DisplayAttribute), false)). But, being an array from a function, I can't see any way to add a DisplayAttribute { Name = MyDisplayName } item to it.

Any help would be very, very appreciated.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
Microsoft Technologies based on the .NET software framework.
3,346 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,031 Reputation points

    Something like this?

    public string Title { get; set; }

    Custom attribute

    public class CustomDisplayAttribute : DisplayNameAttribute
        private string _key;
        public CustomDisplayAttribute(string key)
            _key = key;
        public override string DisplayName => 
                "(\\P{Ll})(\\P{Ll}\\p{Ll})", "$1 $2"), "(\\p{Ll})(\\P{Ll})", "$1 $2");
    0 comments No comments