我已经从sql server创建了一个数据库,并使用了实体框架电动工具为我生成了模型和dbcontext。
它有两个类:
Lookup_System: which is 1st table
Lookup_SubSystem: which is 2nd table with has relationship like: SystemID from Lookup_SubSystem points to SystemID from Lookup_System base table.
我只能从Lookup_SubSystem表中获取数据,因为导航字段始终为null或为空。
难道我做错了什么?
public partial class Lookup_System
{
public Lookup_System()
{
this.Lookup_SubSystem = new List<Lookup_SubSystem>();
}
public long SystemID { get; set; }
public string SystemDesc { get; set; }
public Nullable<bool> IsActive { get; set; }
public Nullable<byte> SOrder { get; set; }
public virtual ICollection<Lookup_SubSystem> Lookup_SubSystem { get; set; }
}
public partial class Lookup_SubSystem
{
public Lookup_SubSystem()
{
this.Lookup_ComponentType = new List<Lookup_ComponentType>();
}
public long SubSystemID { get; set; }
public string SubSystemDesc { get; set; }
public long SystemID { get; set; }
public Nullable<bool> IsActive { get; set; }
public Nullable<byte> SOrder { get; set; }
public virtual ICollection<Lookup_ComponentType> Lookup_ComponentType { get; set; }
public virtual Lookup_System Lookup_System { get; set; }
}
public class Lookup_SubSystemMap : EntityTypeConfiguration<Lookup_SubSystem>
{
public Lookup_SubSystemMap()
{
// Primary Key
this.HasKey(t => t.SubSystemID);
// Properties
this.Property(t => t.SubSystemDesc)
.HasMaxLength(250);
// Table & Column Mappings
this.ToTable("Lookup_SubSystem");
this.Property(t => t.SubSystemID).HasColumnName("SubSystemID");
this.Property(t => t.SubSystemDesc).HasColumnName("SubSystemDesc");
this.Property(t => t.SystemID).HasColumnName("SystemID");
this.Property(t => t.IsActive).HasColumnName("IsActive");
this.Property(t => t.SOrder).HasColumnName("SOrder");
// Relationships
this.HasRequired(t => t.Lookup_System)
.WithMany(t => t.Lookup_SubSystem)
.HasForeignKey(d => d.SystemID);
}
}
public List<Lookup_SubSystem> getAllSubSystems()
{
using (DataContext)
{
var a = (from x in DataContext.Lookup_SubSystem
where x.IsActive == true
orderby x.SOrder ascending
select x);
return a.ToList();
}
}
您应该在数据上下文中启用延迟加载:((IObjectContextAdapter)this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
或在查询数据库时包括导航属性:DataContext.Lookup_SubSystem.Include("Lookup_System")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句