创建一个自定义属性来执行此操作
internal class Metadata
{
[MappingColumn (Type="Key")]
public int ContractId { get; set; }
[Required]
[MappingColumn (Type="Name")]
public string Name { get; set; }
}
使用此签名创建两个方法
string GetKeyColumName(Type type) //will perfom a loop on the type properties custom attribute and return the first with the type Key
string GetNameColumnName(Type type)//will perfom a loop on the type properties custom attribute and return the first with the type Name
using (var context = new IMToolDataContext())
{
ddlContracts.DataValueField = GetKeyColumnName(typeof(Metadata));
ddlContracts.DataTextField = GetNameColumnName(typeof(Metadata));
ddlContracts.DataSource = context
.AllContracts
.OrderBy(o => o.Name);
ddlContracts.DataBind();
}
编辑:
我提到的column属性是yourcunstom属性,而不是Linq中的属性。好的,我应该叫它MappingColumn,它可以这样声明:
public class MappingColumnAttribute : System.Attribute
{
public string Type {get;set;}
}