Given the following class....
namespace IMTool.Data
{
public partial class AllContracts
{
internal class Metadata
{
public int ContractId { get; set; }
[Required]
public string Name { get; set; }
}
}
}
and given the following.
using (var context = new IMToolDataContext())
{
ddlContracts.DataValueField = "ContractId";
ddlContracts.DataTextField = "Name";
ddlContracts.DataSource = context
.AllContracts
.OrderBy(o => o.Name);
ddlContracts.DataBind();
}
How can I strongly type the dropdown list DataValue and the DataText fields? Basically I do not want to use a string but rather the column name from the entity, I am using LinqToSql (well PLinqo which is a codesmith set of templates to generate my datalayer) Can anyone help?
Create a custom attribute to do this
internal class Metadata
{
[MappingColumn (Type="Key")]
public int ContractId { get; set; }
[Required]
[MappingColumn (Type="Name")]
public string Name { get; set; }
}
create two methods with this signature
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
and populate your ddl like this:
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();
}
EDIT: The column attribute I refer is yourcunstom attribute, not the one from Linq. Ok I should have called it MappingColumn it can be declare like this:
public class MappingColumnAttribute : System.Attribute
{
public string Type {get;set;}
}