Alec
Alec

Reputation: 1706

How can I load related objects when reading an object from the database?

I am fairly certain that this is a lazy loading issue, but after reading about lazy loading, I am still no closer to a solution. I have tried turning lazy loading on and off with no success. When I pull a Node from the database, the Parent and Children are null, even though such objects exist in the database.

I also added the 'IsReference = true' as an attempt to solve this issue.

I made the data members that are object references virtual at one point but I had serialization issues with the proxies.

DatabaseContext.cs

public class DatabaseContext : DbContext
{
  public DatabaseContext() : base("DatabaseName")
  {
    Configuration.LazyLoadingEnabled = false;
  }
  public DbSet<Node> Nodes { get; set; }
}

Node.cs

[DataContract(IsReference = true)]
public partial class Node
{

  [DataMember]
  public long ID { get; private set; }

  [DataMember]
  public Node Parent { get; set; }

  [DataMember]
  public ICollection<Node> Children { get; set; }

}

Upvotes: 0

Views: 139

Answers (2)

Alec
Alec

Reputation: 1706

I ended up passing the includes I wanted as parameters (you can use actual types or strings) to the method, and then I looped the includes since they return DbQuery objects and don't actually query the database. Thanks for the input @moi_meme (+1).

foreach (var include in includes)
{
  query = query.Include(include);
}

Upvotes: 0

moi_meme
moi_meme

Reputation: 9318

see Loading Related Objects

the simplest way is to use .Include("Parent").Include("Children") in your query

Upvotes: 2

Related Questions