简体   繁体   中英

Why is Entity Framework returning null?

So I have these classes:

[Table("OrderInfo")]
public class OrderInfo
{
    public long ID {get; set;}
    public long OrderID {get; set;}
    public virtual Order Order { get; set; }
    public long ItemID {get; set;}
    public double Qty { get; set; }
    public virtual Item Item { get; set; }
}

[Table("Items")]
public class Item
{

    public Item()
    {
        this.Orders = new List<OrderInfo>();
    }
    #region Strings
    public string Color { get; set; }
    public string FullName { get; set; }
    [Column(@"Sheet/Roll")]
    public string Type { get; set; }
    public string PrimaryMachine { get; set; }
    public string Alias { get; set; }
    public string Brand { get; set; }

    #endregion

    #region Long
    public long ID { get; set; }
    public long? Weight { get; set; }
    #endregion

    #region Doubles
    public double? Size1 { get; set; }
    public double? Size2 { get; set; }
    public double? Size3 { get; set; }
    #endregion.

    public virtual ICollection<OrderInfo> Orders { get; set; }
}

and when I use the following code it throws NullReferenceException at me and when in debug the null is the Item portion of OrderInfo I can't figure out how to fix this though!

below is the code calling the data:

            int ID = Convert.ToInt32(dgv["ID", dgv.SelectedRows[0].Index].Value);
            List<OrderInfo> OrderInfo = new List<OrderInfo>();
            OrderInfo = c.OrderInfo.Where(x => x.OrderID == ID).ToList();

             if(OrderInfo.Count <= 0)
             {
                MessageBox.Show("No Info Found For This Order!");
                ClearForm();
                return;
             }

            lblPO.Text = "P.O. # " + OrderInfo[0].ID.ToString();
            lblRequestedBy.Text = "Requested By: " + OrderInfo[0].Order.RequestedBy;
            lblOrderDate.Text = "Ordered On: " + OrderInfo[0].Order.Date.ToShortDateString();

            dgvOrderItems.DataSource = OrderInfo.Select(x => new { x.ItemID, x.Qty, x.Item.FullName, x.Item.Brand, x.Item.Color }).ToList();

Entity Framework works lazy by default. You might want to Include your Item when you load your orders. Something like this:

// by using 'Include' you tell EF to fetch Item with your OrderInfo
OrderInfo = c.OrderInfo.Include("Item").Where [...] 

I was able to fix this by changing the Query to also have an Include with the items table using my Navigation Property:

so I changed this line

OrderInfo = c.OrderInfo.Where(x => x.OrderID == ID).ToList();

To

OrderInfo = c.OrderInfo.Include("Item").Where(x => x.OrderID == ID).ToList();

and then it all worked fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM