にアクセスするにはProductionLine
とMachine
の2つのテーブルがあります。 Machine
テーブルでは、という名前のProductionLine
への外部キーがあります。他のテーブルの列に外部キー
Machine
テーブルからKeyId
のProductionLine
にアクセスしたいと思います。 私のマシンクラス:
[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; }
、それはDbContextクラスです:
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();
}
は私が
Object reference not set to an instance of an object.
は、私は何をしなければならないの、このエラーが出るライン
int Mid=...
に、このコードを実行している場合は?
私のテーブルは、EFコード・ファーストによって生成され -ProblemあなたはProductionLine
上記[ForeignKey("ForeignKeyName")]
属性を持っており、それが仮想Lazy Loading
可能にするためにしなければならないマシンのproductionLine
を助けた場合P.S答えとしてそれをマークしてください、あなたはマシンのエンティティタイプの設定やクラス定義を示していただけますか? –
@RichaGarg My Code Is Updated – sadeq
あなたは 'ProductionLine'プロパティに対して' [ForeignKey] '属性について言及していません。外部キーとしてどのように設定していますか? –