Adding Metadata to Schema EF 6.x in C#

C#

If you are one of those shortcut guys like me, and marshal your DB models to your views, then here is a way to add metadata to your models without having the T4 template wipe your added code out.

Comments in green. Related sections of code to take note of have matching colors.

using System;
using System.Collections.Generic;
using System.ComponentModel;
//NOTE the Namespace below
using System.ComponentModel.DataAnnotations; 
using Newtonsoft.Json;
//NOTE the serialization Namespace
using Newtonsoft.Json.Serialization; 

namespace My.Models.Security
{
/* This MetaDataType points to the embedded child class called 
 * ApplicationMetadata.
 * Also keep in mind, the EF templates generate models as partial, 
 * so this class file is actually Application.Metadata.cs, as an 
 * extension of Application.cs. */
    [MetadataType(typeof(ApplicationMetadata))]
    public partial class Application
    {
/* And here is the embedded child class that has all of the 
 * metadata for serialization.
 * Yes, it is a copy of the class file, and serialization properties</span>
 * added, but that is what you have to do to get around template 
 * generated classes that have a tendency to get overwritten. */
        [JsonObject("app")]
        public partial class ApplicationMetadata
        {
            [JsonProperty("name")]
            public string ApplicationName { get; set; }
            [JsonProperty("id")]
            public System.Guid ApplicationId { get; set; }
            [JsonProperty("desc")]
            public string Description { get; set; }

            [JsonIgnore]
            public virtual ICollection Memberships { get; set; }

            [JsonProperty("roles")]
            public virtual ICollection Roles { get; set; }
            [JsonProperty("users")]
            public virtual ICollection Users { get; set; }
            [JsonProperty("uris")]
            public virtual ICollection UriExpressions { get; set; }
        }
    }
}

There are other things you can do, such as using interfaces, customizing your own T4, don’t use schema driven development. But this is one of the simplest for small projects that I have found.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.