I am working on a form to add new inventory into an inventory tracking database I designed. I have done a mapping to EF and I am using LINQ to EF to query data.
The equipment table has a navigation property EquipmentInventories. Consider the following snippet of code:
public partial class Content_AddInventoryItems : System.Web.UI.Page
{
public Equipment equipment;
protected void Page_Load(object sender, EventArgs e)
{
using (MSSInvDBEntities myEntities = new MSSInvDBEntities())
{
var manuPop = (from equipment in myEntities.Equipments
select equipment.equipmentManu).Distinct();
ManuList.DataSource = manuPop;
ManuList.DataBind();
}
using (MSSInvDBEntities myEntities = new MSSInvDBEntities())
{
var modelPop = from equipment in myEntities.Equipments
select equipment.equipmentModel;
ModelList.DataSource = modelPop;
ModelList.DataBind();
}
}
private void DisplayEquipmentData()
{
ManuList.SelectedValue = equipment.equipmentManu;
ModelList.SelectedValue = equipment.equipmentModel;
tboSerial.Text = equipment.EquipmentInventories.serialNumber;
}
}
However I keep getting errors when I try to reference the serialNumber property of the EquipmentInventories object using the EquipmentInventories navigation property of the equipment object.
Any ideas where I went wrong?
I don't see where you instantiate your public field
equipment. (equipmentinfrom equipment in...is another variable, the range variable for the LINQ query.) Looking at your code I'd expect aNullReferenceExceptionbecauseequipmentisnull.You should have something like:
But this would cause an exception as well because you don't load the
equipment.EquipmentInventoriesproperty and lazy loading won't work in yourDisplayEquipmentDatamethod because you already have disposed the context (automatically at the end of theusingblock). Lazy loading requires a context which isn't disposed yet.In your case I would use eager loading though:
Then the navigation property is loaded at once with this query and you can safely dispose the context.