Reputation: 21
I'm using EF4.x, Code First and Castle Windsor for DI. My problem: certain virtual properties are coming back null when retrieving a newly inserted entity. I'm new to this so please forgive my ignorance on how everything works. A very simple example is something like this:
public class Address
{
public int AddressID { get; set; }
public string Street { get; set; }
public int ProvinceID { get; set; }
public virtual Province { get; set; }
etc....
}
public class Province
{
public int ProvinceID { get; set; }
public string Name { get; set; }
public string Abbreviation { get; set; }
public int DisplayOrder { get; set; }
etc...
}
So after SaveChanges(), I can see the records correctly created in the db, but on a subsequent page request that loads the Address entity, the ProvinceID is correctly set, but virtual Province is null. After a rebuild, there are no problems. What am I doing wrong? TIA
MORE INFO:
I am using DbContext in Repository and Unit of Work patterns. I have an abstract EF RepositoryBase class that contains all of the common CRUD methods. Here is example of the common GET methods:
public T Get(params object[] keyValues)
{
return _dbSet.Find(keyValues);
}
public IQueryable<T> Get(Func<T, bool> filter)
{
return _dbSet.Where(filter).AsQueryable();
}
public IQueryable<T> GetAll()
{
return _dbSet.AsQueryable();
}
_dbSet is set like this:
_dbSet = ((DbContext)_context).Set<T>(); // _context is of IDbContext
Maybe something here is causing the strange problem?
Upvotes: 2
Views: 1780
Reputation: 9533
I use next workaround: detach entity and load again
public T Reload<T>(T entity) where T : class, IEntityId
{
((IObjectContextAdapter)_dbContext).ObjectContext.Detach(entity);
return _dbContext.Set<T>().FirstOrDefault(x => x.Id == entity.Id);
}
Upvotes: 0
Reputation: 34238
So you actually have 2 options with EF in terms of navigation property loading, lazy loading and explicit loading. In my experience explicit loading is far better, as it makes it much harder to cause major performance problems.
Ive written an article on navigation properties which you can read here.
To use explicit navigation property loading you use .Include statements to specify which properties to load in each query.
When you use lazyloading I believe you need virtual decorating all nav properties in your context and the database gets queried when you call get on the property.
Upvotes: 2