因此,我有一个简单的数据库,其中有两个表,首先使用实体框架6.02设置了代码。提交表与tbl_lst_Company表具有一对一关系。它们由company和CompanyID字段关联。
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; } }
这是Fluent映射:
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"); }
这是我要测试上述实现的单元测试:
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(); }
我的问题是,运行此测试时,“公司”字段始终为空。如果我从db.Submissions.Include(“ Company”)中的s明确地说,那么Company字段不为null,但我必须急于加载导航属性。我希望公司导航属性延迟加载。据我所知,我正在按应有的方式做所有事情,但是没有用。我究竟做错了什么?
谢谢
因此我想出了很多错误,但这是对我有用的解决方案。您无需实例化单个导航属性。这将使其始终为空。如果它是对象的ICollection,则仍然需要实例化Navigation属性。还有其他一些小事情。谢谢您的帮助。
public partial class Submission { public int Keytbl { get; set; } public int Company { get; set; } public virtual tbl_lst_Company tbl_lst_Company{ get; set; } } public partial class tbl_lst_Company { public tbl_lst_Company() { this.Submissions = new List<Submission>(); } public int CompanyID { get; set; } public string Company { get; set; } public virtual ICollection<Submission> Submissions { get; set; } } 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"); } 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.Company).HasColumnName("Company"); this.HasOptional(t => t.tbl_lst_Company) .WithMany(t => t.Submissions) .HasForeignKey(d => d.Company); } [TestMethod] public void test_lazy_loading() { using (var db = new SubmissionContext()) { var subs = (from s in b.Submissions select s); var x = subs.First().tbl_lst_Company; Assert.AreEqual(x, null, "Lazy Loading Failed"); } }