Thursday, January 9, 2014

I love the word The

Want to enforce SchemaName.TableName to your domain models (think AdventureWorks)? i.e., you wanted this:

var personList = 
    from p in session.Query<Person.Person>
    select p;

var storeList = 
    from s in session.Query<Sales.Store>
    select s;


You can't use namespace..

namespace Domain.Models
{
    namespace Person
    {
        public class Person
        {
        }
        public class BusinessEntityContact
        {
        }
    }


    namespace Sales
    {
        public class Store
        {
        }
    }
}


..as developers can opt out of Person or Sales namespace by importing the namespace through C#'s using, some would do this:

using Domain.Models.Sales;


.
.
.


var list = 
    from p in session.Query<Store>
    select p;




To achieve enforcement of Schema name on your domain classes, do this instead:

namespace Domain.Models
{
    public static class Person
    {
        public class Person
        {
        }
    
        public class BusinessEntityContact
        {
        }
    }

    public static class Sales
    {
        public class Store
        {
        }
    }
}

However that will not work, it's not allowed for the nested class to have the same name as its containing class, e.g., Person.Person. So we must use some convention to eliminate the compiler error through naming convention, e.g.:


namespace Domain.Models
{
    public static class PersonSchema
    {
        public class Person
        {
        }
    
        public class BusinessEntityContact
        {
        }
    }

    public static class SalesSchema
    {
        public class Store
        {
        }
    }
}

But I prefer prefixing the word The:


namespace Domain.Models
{
    public static class ThePerson
    {
        public class Person
        {
        }
    
        public class BusinessEntityContact
        {
        }
    }

    public static class TheSales
    {
        public class Store
        {
        }
    }
}


Using that convention, reading the code rolls off the tongue quite nicely:


var personList = 
    from p in session.Query<ThePerson.Person>
    select p;

var businessContactList = 
    from c in session.Query<ThePerson.BusinessContact>
    select c;


var storeList = 
    from s in session.Query<TheSales.Store>
    select s;


Sorry Entity Framework, the Set method doesn't cut it:

var list = 
    from s in context.Set<TheSales.Store>
    select s;


Happy Coding! ツ

1 comment:

  1. Nice trick! I'm also a fan of short and creative prefixes and suffixes.

    My last creation was "RedirectByUs" when I wrapped the Response.Redirect() method in ASP.NET ;-)

    ReplyDelete