Adding Metadata to Schema EF 6.x in 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. */
    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. */
        public partial class ApplicationMetadata
            public string ApplicationName { get; set; }
            public System.Guid ApplicationId { get; set; }
            public string Description { get; set; }

            public virtual ICollection Memberships { get; set; }

            public virtual ICollection Roles { get; set; }
            public virtual ICollection Users { get; set; }
            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: Logo

You are commenting using your 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.