DropDownList DataTextField on Navigation property

1.8k views Asked by At

i need some help with the following.

i get a list of objects from the Entity Framework data context.

var list = context.EntityA;

the EntityA is the main object (contains the primary key), but has a navigation property called "EntityALanguages", which contains language specific properties.

now i want to bind the list to a dropdownlist and need so set DataValueField and DataTextField properties from the dropdownlist.

how can i set the DataTextField to a property of a navigation property, something like:

this.ddl.DataValueField = "GUID";
this.ddl.DataTextField = "EntityALanguages.ShortDescription";

Edit: The navigation property "EntityALanguages" is a collection, so EntityA -> EntityALanguages is a 1-n relation

3

There are 3 answers

2
DaveB On

By using var list = context.EntityA; your navigation properties will be lazy loaded. Try var list = context.EntityA.Include("EntityALanguages"); so your navigation propery will be present.

0
AGULA On

In your entity EntityALanguages you could add a readonly property like this

public readonly string EntityALanguagesShortDescription
{
    get { return this.EntityALanguages.ShortDescription; }
}
0
Pablogrind On

DropDownList may not support propertytrees for binding.

What you could do if you want to bind is to do the following:

var items = context.Entity.Include("EntityALanguages").Select(row => new { Id = row.GUID, Name = row.EntityALanguages.ShortDescription}).ToList();

ddl.DataTextField = "Name"; ddl.DataValueField = "Id";