【发布时间】:2015-01-12 15:10:10
【问题描述】:
非常奇怪的问题,我在很多项目中都使用 EF + Code First,但我不知道这里发生了什么。
我有以下实体:
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;}
}
使用以下 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);
}
}
这里没什么特别的,但是每当我检索到这样的文章时:
var article = _db.Articles.FirstOrDefault(x => x.ID == id);
我有两个问题这是我的问题:
- 图像导航属性为空。它不是 null,但它的所有属性都有默认值(0、null 等...)
Article 对象具有动态代理,但导航属性 Image 和Employees 没有。如果我没记错的话,导航属性默认应该被动态代理包装。- 需要注意的重要一点是,Employee 导航属性的所有属性都已正确加载。这很好,但是上面没有动态代理。
过去 2 小时我一直在尝试解决此问题,但我没有办法了。
我将不胜感激任何提示/帮助,
谢谢!
更新:我查过数据库,外键没问题,Images表中的记录确实存在。
【问题讨论】:
标签: c# asp.net-mvc entity-framework ef-code-first asp.net-mvc-5