如何使用外键访问其他表的列

时间:2016-08-09 05:40:39

标签: c# entity-framework

我有两张表ProductionLineMachine。在Machine表格中,我有一个名为ProductionLine的{​​{1}}的外键。

我想从productionLine表格访问KeyId中的列ProductionLine。 我的机器类:

Machine

和那个DbContext类:

[Column("FldKeyId")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    [Key]
    public int MyKeyId { get; set; }
    [Column("FldCode")]
    [Required]
    [Index(IsUnique = true)]
    public int MyMachineCode
    {
        get { return _MachineCode; }
        set { _MachineCode = value; }
    }
    [Column("FldName")]
    [Required]
    public string MyName
    {
        get { return _Name; }
        set { _Name = value; }
    }
    [Column("FldDescription")]
    [Required]
    public string MyDescription
    {
        get { return _Desc; }
        set { _Desc = value; }
    }
    [Column("FldModifiedUserId")]
    [Required]
    public int ModifiedUserId { get; set; }
    [Column("FldModificationDate")]
    [Required]
    public DateTime ModificationDate { get; set; }
    [Column("FldDeleteFlag")]
    [Required]
    public int DeleteFlag { get; set; }
    [Required]
    public ProductionLine ProductionLine { get; set; }

我有这段代码,但是它引发了一个错误:

public DbSet<Machine> Machines { get; set; }

和方法Machine _SelectedMachine; _SelectedMachine = (cmbMachines.SelectedItem as Machine); int Mid = _SelectedMachine.ProductionLine.MyKeyId; dgvcolCompany.DataSource = ProductionLine.GetMachineLine(Mid);

getMachineLine

运行此代码时,行

public static List<ProductionLine> GetMachineLine(int KeyId)
{
   return new ContexManager().ProductionLines.Where(c => c.MyKeyId == KeyId && c.DeleteFlag == 0).ToList();
}

我收到此错误

  

对象引用未设置为对象的实例。

我该怎么做?

我的表格是由EF代码优先生成的  -Problem是如何从Machine的生产线访问ProductionLine的KeyId

2 个答案:

答案 0 :(得分:1)

将属性ProductionLine声明为虚拟。还要在其上添加外键属性。

[ForeignKey]

public virtual ProductionLine ProductionLine;

如果有帮助,请将其标记为答案

答案 1 :(得分:0)

您必须拥有[ForeignKey("ForeignKeyName")]以上ProductionLine属性 并使其虚拟化以使Lazy Loading成为可能。或者,如果您不想在延迟加载时使用Include("ProductionLine")来获取计算机。

OffTopic:你的名字不好。实体框架使用“公约”方法。因此,永远不应将名为Machine的类的主键称为MyKeyId

相关问题