1
我試圖訪問一些使用導航屬性的相關實體。我已關閉延遲加載,並正在使用Include()
方法可用using System.Data.Entity
加載相關實體。但是,當視圖加載時,我的相關實體爲null。EF 4.3反向代碼優先:渴望加載的相關實體爲空
我相信關係已正確配置我錯過了什麼?
調用方法
public IQueryable<JobRecord> GetAll()
{
return _dataContext.Set<JobRecord>()
.Include(t => t.CompanyInfo);
}
語境
public class Application_Context : DbContext, IDataContext
{
public Gyroview_Context():base("Application_Entities")
{
Database.SetInitializer<Application_Context>(null);
Configuration.LazyLoadingEnabled = false;
}
public DbSet<CompanyInfo> CompanyInfoes { get; set; }
public DbSet<JobRecord> JobRecords { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CompanyInfoMap());
modelBuilder.Configurations.Add(new JobRecordMap());
modelBuilder.Entity<JobRecord>()
.HasOptional(r => r.CompanyInfo)
.WithMany(c => c.JobRecords)
.HasForeignKey(r => r.CompanyID);
}
public IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
}
JobRecord
public class JobRecord
{
public JobRecord()
{
this.CompanyInfo = new CompanyInfo();
}
public Nullable<int> CompanyID { get; set; }
public int Jobid { get; set; }
public virtual CompanyInfo CompanyInfo { get; set; }
}
JobRecord地圖
public class JobRecordMap : EntityTypeConfiguration<JobRecord>
{
public JobRecordMap()
{
// Primary Key
this.HasKey(t => t.Jobid);
// Table & Column Mappings
this.ToTable("JobRecord");
this.Property(t => t.CompanyID).HasColumnName("CompanyID");
this.Property(t => t.Jobid).HasColumnName("Jobid");
// Relationships
this.HasOptional(t => t.CompanyInfo)
.WithMany(t => t.JobRecords)
.HasForeignKey(d => d.CompanyID);
}
}
公司信息
public class CompanyInfo
{
public CompanyInfo()
{
this.JobRecords = new List<JobRecord>();
}
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
public virtual ICollection<JobRecord> JobRecords { get; set; }
}
公司信息地圖
public class CompanyInfoMap : EntityTypeConfiguration<RigViewCompanyInfo>
{
public CompanyInfoMap()
{
// Primary Key
this.HasKey(t => t.CompanyID);
// Properties
this.Property(t => t.CompanyName)
.HasMaxLength(255);
this.Property(t => t.Address)
.HasMaxLength(255);
// Table & Column Mappings
this.Property(t => t.CompanyID).HasColumnName("CompanyID");
this.ToTable("CompanyInfo");
this.Property(t => t.CompanyName).HasColumnName("CompanyName");
this.Property(t => t.Address).HasColumnName("Address");
}
}