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

Graeme Smith 1 Reputation point
2022-01-20T11:02:20.363+00:00

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
.NET
.NET
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
    2022-01-30T18:26:43.957+00:00

    Something like this?

    public string Title { get; set; }
    [CustomDisplay("DateModified")]
    

    Custom attribute

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