将“友好”列名添加到LINQ to SQL模型的好方法是什么?

时间:2009-01-11 13:18:34

标签: c# sql linq

我有一个LINQ to SQL模型设置 - 但是在我的应用程序中,某些地方我需要“友好”列名称,例如:

“NameFirst”成为“名字” “AgencyName”为“Agency”

只是寻找关于创建这些映射的最佳位置/技术的建议 - 不改变模型。这些映射不一定会在GridView或任何控件中使用 - 希望它们以任何容量可用。

谢谢!

2 个答案:

答案 0 :(得分:2)

嗯,对于大多数表格使用,你需要[DisplayName(...)],但如果不搞乱部分类就不容易做到。但是,如果您只是希望它可用,您可以针对该类声明自己的属性,并将其添加到那里:

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

然后使用反射来解决它;那呢?如果是这样的话,那就像:

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; }
}

答案 1 :(得分:0)

另一种选择是维护一个字符串字典,其中属性名称(Type.Property)作为键,友好名称作为值。

然后,您可以在静态类中进行设置,并在需要时随时使用它。这很容易维护,因为您可以在一个地方获得所有定义。

您甚至可以将它作为实体基类的静态属性,以便它可用于所有实体类型。