c# - 将 "friendly"列名添加到 LINQ to SQL 模型的好方法是什么?

标签 c# sql linq

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

“NameFirst”为“First Name” "AgencyName"为 "Agency"

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

谢谢!

最佳答案

嗯,对于大多数表格使用,您需要 [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; }
}

关于c# - 将 "friendly"列名添加到 LINQ to SQL 模型的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/432913/

相关文章:

c# - 离开加入 Linq?

c# - 我可以从数据库中检索艺术家、名称和流派,但不能检索价格。检索价格的代码应该是什么?

c# - 从现有类生成接口(interface)

sql - 插入 id(自动生成,仅列)

.net - SQL Server 和 .NET : insert fails (silently! ) 在代码中,但在手动运行时不是

c# - C# 中的 TypeScript "map"函数?

c# - 如何使用查询字符串测试 URL 的路由/操作解析?

c# - 如何使用用于 DocumentDb 单元测试的过滤器来模拟 DocumentClient CreateDocumentQuery?

查询中的 MySQL 存储过程

c# - 1 个 LINQ 查询中的多个对象初始值设定项