如何将gridview绑定到表有一个外键

时间:2016-08-18 07:30:39

标签: c# datagridview ef-code-first

我的表有3个foregin键现在我想在gridview中显示表的类:

[Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("FldKeyId")]
    public int MyKeyId { get; set; }
    [Required]
    public virtual Machine Machine { get; set; }  
    [Required]
    public virtual Employee Employee { get; set; }
    [Required]
    public virtual Shift Shift { get; set; }
    [Required]
    [Column ("FldStartTime")]
    public DateTime MyStartTime { get; set; }
    [Required]
    [Column ("FldEndTime")]
    public DateTime MyEndTime { get; set; }
    [Column("FldModificationDate")]
    [Required]
    public DateTime ModificationDate { get; set; }

,这是绑定到网格视图的代码

void RefreshBreakGrid()
    {
        dgvcolDate.DataPropertyName = "ModificationDate";
        dgvcolstarttime.DataPropertyName = "MyStartTime";
        dgvcolendtime.DataPropertyName = "MyEndTime";

        dgvcolemployee.DataSource = Employee.GetAllEmployee();
        dgvcolemployee.DisplayMember = "MyName";
        dgvcolemployee.ValueMember = "MyKeyId";
        dgvcolemployee.DataPropertyName = "Employee";


        dgvcolmachine.DataSource = Machine.GetAllMachine();
        dgvcolmachine.DisplayMember = "MyName";
        dgvcolmachine.ValueMember = "MyKeyId";
        dgvcolmachine.DataPropertyName = "Machine";

        dgvcolshift.DataSource = Shift.GetAllShift();
        dgvcolshift.DisplayMember = "MyName";
        dgvcolshift.ValueMember = "MyKeyId";
        dgvcolshift.DataPropertyName = "Shift";

        _Breaks=Break.GetAllBreak();
        dgvBreak.AutoGenerateColumns = false;
        dgvBreak.DataSource = _Breaks;
    }

例如getall公司的方法:

public static List<Break> GetAllBreak()
{
    return new ContexManager().Breaks.Where(c => c.MyKeyId != 0).Include(c => c.Machine).Include(c => c.Employee).Include(c => c.Shift).ToList();
}

当我运行此代码时,显示classLibrary.classes.shift来自移位字段的网格视图,我必须做的是在gridview中显示当前值。 我使用winforms和

1 个答案:

答案 0 :(得分:0)

使用每个类的覆盖toString()方法解决它