Very strange issue, I've been using EF + Code First on a lot of projects but I can't figure out what's going on here.
I have the following entities :
public class Article { public int ID { get; set; } public string Title { get; set; } public virtual Media Image{ get; set; } public virtual Employee Author {get; set;} public MyEnum EnumValue {get; set;} public enum MyEnum {Value1, Value2} } public class Media { public int ID {get; set;} public double Length { get; set; } public string ContentType { get; set; } public byte[] Content { get; set; } } public class Employee { public int ID {get; set;} public string Name{get; set;} public string Email{get; set;} } With the following DbContext :
public class MyContext : DbContext { public MyContext() : base("ConnectionString") { this.Configuration.LazyLoadingEnabled = true; this.Configuration.ProxyCreationEnabled = true; } public DbSet<Article> Articles { get; set; } public DbSet<Employee> Employees { get; set; } public DbSet<Media> Medias { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Article>().HasRequired(x => x.Image); modelBuilder.Entity<Article>().HasOptional(x => x.Author); } } Nothing special here, however whenever I retrieve an Article for example like that :
var article = _db.Articles.FirstOrDefault(x => x.ID == id); I have two problems Here is my problem :
- The Image navigation property is empty. It is not null but all its properties have default values (0, null, etc...)
The Article object has a dynamic proxy but the navigation properties Image and Employees do not. If I remember correctly, navigations properties should be wrapped by dynamic proxies by default.- One important thing to note is that, the Employee navigation property has all its properties correctly loaded. This is good, however there is no dynamic proxy on it.
I've spent the last 2 hours trying to troubleshoot this and I'm running out of idea.
I would appreciate any hint / help,
Thanks !
Update : I've checked in the database and the foreign key is OK and the record in the Images table does exist.