In Entity Framework, I have a class Order:
public class Order
{
public Order()
{
this.Info = new HashSet<OrderInfo>();
}
[Required]
public int Id { get; set; }
[NotNull, MapTo("RecordId")]
public virtual ICollection<OrderInfo> Info { get; set; }
}
with a one-to-many relationship to the class OrderInfo:
public class OrderInfo
{
public OrderInfo() { }
public int RecordId { get; set; }
}
In my OrderInfo table, RecordId
is the foreign key that corresponds to the Order's Id
column (Order's primary key).
I am creating an Order object, then creating an OrderInfo that will map to the order. Like so:
using (var context = new MyDbContextClass())
{
// method that creates an Order, adds it to the context's change tracker
// and returns the order's Id
var orderId = await CreateOrder();
// method that creates an OrderInfo with orderId as its RecordId
// and adds it to the context's change tracker
await CreateOrderInfo(orderId, "Order info contents");
// calls DbContext.SaveChanges()
await context.Commit();
var order = context.Order.Find(orderId);
var associatedOrderInfo = order.Info;
var queriedOrderInfo = context.OrderInfo.Where(info => info.RecordId == orderId);
}
associatedOrderInfo
is always empty, and queriedOrderInfo
always has the expected values. Also, if I then open a new context and retrieve the order by Id again, its Info contains the expected values.
I have confirmed the following:
context.Configuration.ProxyCreationEnabled
is true (verified with debugger)context.Configuration.LazyLoadingEnabled
is true (verified with debugger)- The navigation property is declared
public virtual
- The type referenced in the navigation property has a public, parameterless constructor.
From my understanding of lazy loading, it queries the database for OrderInfo objects who have the order's Id as their RecordId. At this point, the data has been committed and my isolation level is read-committed. Therefore, the order should give me related OrderInfo objects the first time I ask, and not make me open a new context to find them. Why does it come back empty?
Edit:
I have also attempted to force lazy initialization of the navigation properties as in this question. Here is my order class:
public class Order
{
public Order()
{
}
[Required]
public int Id { get; set; }
private ICollection<OrderInfo> _Info;
[NotNull, MapTo("RecordId")]
public virtual ICollection<OrderInfo> Info
{
get
{
return this._Info ?? (this._Info= new HashSet<OrderInfo>());
}
set
{
this._Info = value;
}
}
}
Even with this implementation of order, it comes back empty.