asp:DropDownList Linq-to-sql 数据源绑定文本字段到关系-属性 值

asp:DropDownList Linq-to-sql data source binding text field to relation-property value

所以我正在使用 Linq-to-sql 与我的 sql 服务器通信,我想用我的数据库中的数据填充 asp.net 下拉列表。问题是我希望用户可见的文本值绑定到一个关系-属性。

我有一个 linq-to-sql 对象列表,每个对象都有一个一对多的父子关系 属性。 parent属性 简称为 "parent",它也是一个 linq-to-sql 对象,包含字符串类型的名称 属性。问题是我想将 DataTextField 绑定到 parent.name 属性.

下面的代码来自我的代码隐藏文件,该文件在 DropDownList 是我的下拉列表和 Table.GetAll() returns linq-to-[=43 列表的那一刻不起作用=] 对象:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Bind_Drop_Down();
    }
}
protected void Bind_Drop_Down()
{
    List<linq-to-sql-class-name> objects = Table.GetAll();
    if (objects != null)
    {
        DropDownList.DataSource = objects;
        DropDownList.DataTextField = "parent.name";
        DropDownList.DataValueField = "id";
        DropDownList.DataBind();
    }
}

我认为这可以通过将原始查询放在我的数据库的正上方这段代码并使其创建一个具有新参数的新对象来解决,但我不想要这个。我想将原始查询保留在我的 Table class 中,它应该只 return 正确的 linq-to-sql 对象。

我在执行上面的代码时收到以下错误消息,其中 linq-to-sql-class-name 是实际名称的占位符:

DataBinding: 'linq-to-sql-class-name' does not contain a property with the name 'parent.name'

我的问题是:这可以做到吗?

编辑:

我添加了一些代码来验证 属性 是否确实存在,我尝试打印列表中每个对象的 parent.name 属性 并且它确实按预期打印了它。

protected void Bind_Drop_Down()
{
    List<linq-to-sql-class-name> objects = Table.GetAll();
    if (objects != null)
    {
        foreach(linq-to-sql-class-name oneObject in objects)
        {
            System.Diagnostics.Debug.WriteLine(oneObject.parent.name);
        }
        DropDownList.DataSource = objects;
        DropDownList.DataTextField = "parent.name";
        DropDownList.DataValueField = "id";
        DropDownList.DataBind();
    }
}

它在调试控制台中打印了这个:

name1 lastname1
name2 lastname2
...etc
...etc

当然,我在发布这个问题后立即找到了合适的解决方案: