如何首先使用实体​​框架数据库检索模型中的导航数据

时间:2014-02-27 06:21:27

标签: c# entity-framework

我已经从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表中获取数据,因为导航字段始终为空或空。

我做错了吗?

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();
    }
}

1 个答案:

答案 0 :(得分:1)

您应该在datacontext中启用延迟加载: ((IObjectContextAdapter)this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
或在查询数据库时包含导航属性: DataContext.Lookup_SubSystem.Include("Lookup_System")