tags:

views:

79

answers:

2

I have a LINQ to SQL model setup - however in my app there are certain places where I want "friendly" column names for example:

"NameFirst" to be "First Name" "AgencyName" to be "Agency"

Just looking for suggestions on where the best place/technique to create these mappings would be - without changing the model. These mappings won't necessarily be used in a GridView or any control in particular - want them to be available in any capacity.

Thanks!

+1  A: 

Well, for most table use, you'd need [DisplayName(...)], but this isn't easy to do without messing with the partial classes. However, if you just want it available, you could declare your own attribute against the class, and add it there:

[MyDisplayName("NameFirst", "First Name")]
[MyDisplayName("AgencyName", "Agency")]
partial class Foo {}

Then use reflection to get it out; that do? If so, something like:

static class Program
{
    static void Main()
    {
        Console.WriteLine(MyDisplayNameAttribute.Get(
            typeof(Foo), "NameFirst"));
        Console.WriteLine(MyDisplayNameAttribute.Get(
            typeof(Foo), "Bar"));
    }
}

[AttributeUsage(AttributeTargets.Interface |
    AttributeTargets.Class | AttributeTargets.Struct,
    AllowMultiple = true, Inherited = true)]
sealed class MyDisplayNameAttribute : Attribute
{
    public string MemberName { get; private set; }
    public string DisplayName { get; private set; }
    public MyDisplayNameAttribute(string memberName, string displayName)
    {
        MemberName = memberName;
        DisplayName = displayName;
    }
    public static string Get(Type type, string memberName)
    {
        var attrib = type.GetCustomAttributes(
                typeof(MyDisplayNameAttribute), true)
            .Cast<MyDisplayNameAttribute>()
            .Where(x => x.MemberName.Equals(memberName,
                StringComparison.InvariantCultureIgnoreCase))
            .FirstOrDefault();
        return attrib == null ? memberName : attrib.DisplayName;
    }
}

[MyDisplayName("NameFirst", "First Name")]
[MyDisplayName("AgencyName", "Agency")]
partial class Foo { } // your half of the entity

partial class Foo { // LINQ-generated
    public string NameFirst {get;set;}
    public string AgencyName {get;set;}
    public string Bar { get; set; }
}
Marc Gravell
A: 

Another option would be to maintain a string dictionary with the property names (Type.Property) as the key and the friendly name as the value.

Then you could set it up in a static class and have it available whenever you needed it. This would be easy to maintain since you would have all definitions available in one place.

You could even have it as a static property of your entities base class so that it was available for all entity types.

Rune Grimstad