在EF中连接两个属性以填充ComboBox

时间:2014-12-11 00:39:59

标签: c# .net winforms linq entity-framework

我正在使用Entity Framework,C#和.NET 4.5开发一个新的WinForms项目。在我的数据库中,我有一张桌子'老师'有两列' FirstName'和'姓氏'。我怎么能用这两个属性的值填充ComboBox控件?

情景:

private List<Teacher> ShowTeacher(String teacherID) 
{
   List<Teacher> teachers = (from teacher in context.Teacher 
                            select teacher).Where(t => t.UserID == teacherID).ToList();
   return teachers;  
}

ComboBox中的代码片段:

cmbTeacher.DataSource = ShowTeacher(teacherID);
cmbTeacher.DisplayMember = ""; //here should be placed the string "FisrtName"+"LastName"

提前致谢

1 个答案:

答案 0 :(得分:1)

您需要在数据源中包含fullname值

List<Teacher> teachers = (from teacher in context.Teacher 
                          let FullName = teacher.FirstName + " " + teacher.LastName
                          select teacher).Where(t => t.UserID == teacherID).ToList();

cmbTeacher.DataSource = ShowTeacher(teacherID);
cmbTeacher.DisplayMember = "FullName";

class Teacher 
{
    public string FirstName
    {
        get;
        set;
    }

    public string LastName
    {
        get;
        set;
    }

    public string FullName
    {
        get
        {
            return LastName + " " + FirstName;
        }
    }

    public Teacher(string firstname, string lastname)
    {
        FirstName = firstname;
        LastName = lastname;
    }
}