views:

95

answers:

1

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?

+2  A: 

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;}
}
Gregoire
@Gregoire.... Thanks for this but I am having several problems implementing it. When I add [Column(Type="Key")] I get the error 'System.Data.Linq.Mapping.ColumnAttribute' does not contain a definition for 'Type'
Rippo
I am using the namespace using System.ComponentModel.DataAnnotations;
Rippo
@Rippo See my edit
Gregoire
Finally got there, after looking through some examples of looping through the attributes, thanks. This all seems a bit of a long winded way to do this! But it works!
Rippo