我有一个 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/