[英]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! 当我使用以下代码时,它向我抛出
NullReferenceException
,而在调试中,null是OrderInfo
的Item部分,但我不知道如何解决此问题!
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. 您可能希望在加载订单时
Include
Item
。 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: 我可以通过使用“导航属性”将查询更改为在items表中
Include
一个Include
来解决此问题:
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. 然后一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.