So I have a simple database with two tables setup with code first using entity framework 6.02. The Submission table has a one to one relationship with the tbl_lst_Company table. They are related by the company and CompanyID fields.
public partial class Submission
{
public Submission()
{
this.Company = new tbl_lst_Company();
}
public int Keytbl { get; set; }
public int companyid { get; set; }
public virtual tbl_lst_Company Company { get; set; }
}
public partial class tbl_lst_Company
{
public int CompanyID { get; set; }
public string Company { get; set; }
public virtual Submission Submission { get; set; }
}
And here are the Fluent mappings:
public SubmissionMap()
{
// Primary Key
this.HasKey(t => t.Keytbl);
// Table & Column Mappings
this.ToTable("Submissions");
this.Property(t => t.Keytbl).HasColumnName("Keytbl");
this.Property(t => t.companyid).HasColumnName("company");
this.HasRequired(q => q.Company).
WithOptional().Map(t => t.MapKey("Company"));
}
public tbl_lst_CompanyMap()
{
// Primary Key
this.HasKey(t => t.CompanyID);
// Properties
this.Property(t => t.Company)
.IsRequired()
.HasMaxLength(150);
// Table & Column Mappings
this.ToTable("tbl_lst_Company");
this.Property(t => t.CompanyID).HasColumnName("CompanyID");
this.Property(t => t.Company).HasColumnName("Company");
}
Here is my unit test I am running to test the above implementation:
public void download_data() {
var db = new SubmissionContext();
db.Configuration.LazyLoadingEnabled = true;
var subs = (from s in db.Submissions
select s).Take(100);
var x = subs.First().Company;
var a = subs.ToArray();
}
My problem is that the Company field is always null when I run this test. If I explicilty say from s in db.Submissions.Include("Company"), then the Company field is not null but I have to eager load the navigation property. I want the Company navigation property to lazy load. As far as I can tell I am doing everything the way it is suppose to be done but it is not working. What am I doing wrong?
Thanks
Companyreallynullor is it an uninitialized object? I see that you instantiate the navigation property in theSubmissionconstructor (this.Company = new tbl_lst_Company();) which is not good. You should remove this line in any case. However, I'm not sure if it will solve your particular problem here. - Slaumaxin your example? Is it the expected company or null or do you get an exception on that line as well? - Slauma