当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net - Properly using the Navigation Property in Entity Framework

问题描述:

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. (equipment in from equipment in... is another variable, the range variable for the LINQ query.) Looking at your code I'd expect a NullReferenceException because equipment is null.

You should have something like:

using (MSSInvDBEntities myEntities = new MSSInvDBEntities())
{
    equipment = (from e in myEntities.Equipments
                 select e)
                .FirstOrDefault();
}

But this would cause an exception as well because you don't load the equipment.EquipmentInventories property and lazy loading won't work in your DisplayEquipmentData method because you already have disposed the context (automatically at the end of the using block). Lazy loading requires a context which isn't disposed yet.

In your case I would use eager loading though:

using (MSSInvDBEntities myEntities = new MSSInvDBEntities())
{
    equipment = (from e in myEntities.Equipments.Include("EquipmentInventories")
                 select e)
                .FirstOrDefault();
}

Then the navigation property is loaded at once with this query and you can safely dispose the context.

网友答案:

What Slauma said, or...

private void DisplayEquipmentData() 
{ 
    ManuList.SelectedValue = equipment.equipmentManu; 
    ModelList.SelectedValue = equipment.equipmentModel; 
    if (!equipment.EquipmentInventoriesReference.IsLoaded)
        equipment.EquipmentInventoriesReference.Load();
    tboSerial.Text = equipment.EquipmentInventories.serialNumber; 

} 
分享给朋友:
您可能感兴趣的文章:
随机阅读: