Reputation: 35
I have a generic class that has a Get method using Find to find an entity from the database. It is working but it is not including the other entities that are found in the object.
Example:
public class GenericRepository<TEntity> where TEntity : class
{
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
}
An entity that can be found in the retrieved object which for instance is named User a profile entity can be found but it is null. I need it included when I return the object. Any ideas?
Upvotes: 1
Views: 286
Reputation: 5053
The marked answer will work as long as you are ok with lazy loading of entities.
If you are wanting to eagerly load instead, an alternative would be to write a generic including function like such:
public IQueryable<TEntity> Including(params Expression<Func<TEntity, object>>[] _includeProperties)
{
IQueryable<TEntity> query = m_context.Set<TEntity>();
return _includeProperties.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));
}
which could be used to achieve something similar, the only issue if you have to know the related entities to load. The usage is something like this:
myEntity returnedEntity = myEntityRepository
.Including(x => x.Child1, x => x.Child2)
.FirstOrDefault(x => x.Id == id);
Upvotes: 0
Reputation: 4040
You have to mark your navigation properties as virtual
.
public class User
{
public int ChildID;
public virtual Child ChildEntity;
}
The virtual
keyword will mark your property so that it will be lazy loaded when accessed.
Upvotes: 1