Saturday, 7 September 2013

EntityFramework Not Loading Related Data

EntityFramework Not Loading Related Data

I have these entities:
public class Company : PrimaryKey
{
public string Name {get;set;}
public virtual Account Account {get;set;}
}
public class Account
{
[Key]
public Guid CompanyId { get; set; }
public virtual Company Company {get;set;}
}
I use these configurations:
modelBuilder.Entity<Company>()
.HasOptional(c => c.Account)
.WithRequired(a => a.Company)
.WillCascadeOnDelete();
Now, I have two projects, one is a test bench project which is a Console
Application with a DbContext and a Repository, the second is the full
blown production project which is a MVC 4 in which I use Dependancy
Injection to create a Repository .InTransientScope() which in turn loads a
new context each time it is called.
Both have exactly the same contexts and repositories (the product
obviously has Interfaces).
in the test bench when I call this:
_repository.GetById<Company>(id);
All of it properties are filled out, i.e. eager loading
in the production when I call the same line, nothing is loaded and its not
loaded till I created another function which does this:
_dbContext.Companies.Include("Account").FirstOrDefault(x => x.Id.Equals(id));
Of which, when executed does provide all the Account information, but
funnily bar any other navigation properties that Account contains!!! Even
though I have disable LazyLoading, it still doesn't work.
This is surprising because both projects are fundamentally the same, bar
the use of the IoC DI in one of them....
Why is this happening? How can I specify in a predominantly generic
Repository to eager load all this information at the Controllers
preference....?
Break Points I set break points in both projects too look at the ADO.NET
call to the database and the sql statement that was executed, in the test
bench it did go off and call the information, in the production it did not
show any joins or anything of that nature what so ever.

No comments:

Post a Comment