1
 [Table("Employee", Schema = "Master")]
public class Employee : Common
{
    #region Properties

    [Required]
    [Key]
    public int EmployeeID { get; set; }


    public virtual Department Department { get; set; }
    public int? DepartmentId { get; set; }


    #endregion
}


[Table("Department", Schema = "Lookup")]
public class Department : Common
{
    [Required]
    [Key]
    public int DepartmentId { get; set; }
    [Required]
    [StringLength(50)]
    public string Value { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Employee> Employees { get; set; }
}

获取数据 var employee = CemexDb.Employee.Where(w => w.EmployeeID == employeeId).FirstOrDefault();

当我获取数据时,部门始终为空

请提出解决方法

这是我的代码上下文类中的上下文类

   public class CemexDb : DbContext
{

    public virtual IDbSet<T> DbSet<T>() where T : class
    {
        return Set<T>();
    }
    public CemexDb() : base(ConfigurationManager.ConnectionStrings["CemexDb"].ConnectionString)
    {
        this.Configuration.LazyLoadingEnabled = true;
        this.Configuration.ProxyCreationEnabled = true;
    } 

    public CemexDb(string connectionString): base(connectionString)
    {
        this.Configuration.LazyLoadingEnabled = true;
        this.Configuration.ProxyCreationEnabled = true;
    }


    public virtual void Commit()
    {
        base.SaveChanges();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        Database.SetInitializer<CemexDb>(null);
    }

}

这是访问代码

 public class EmployeeService : RepositoryBase, IEmployeeService
{
    public EmployeeService(IDatabaseFactory DbFactory): base(DbFactory)
    { }

}

存储库基类

    public abstract class RepositoryBase 
{
    private CemexDb db;

    /// <summary>
    /// Holds a reference to the DatabaseFactory class used to manage connections to the database.
    /// </summary>
    protected IDatabaseFactory DatabaseFactory { get; private set; }
    /// <summary>
    /// Contains a reference to the <see cref="System.Data.Entity.DbContext"/> instance used by the repository.
    /// </summary>
    protected CemexDb CemexDb { get { return db ?? (db = DatabaseFactory.Get()); } }

    /// <summary>
    /// Initialises a new instance of the RepositoryBase class.
    /// </summary>
    /// <param name="DbFactory">A valid DatabaseFactory <see cref="Opendesk.Data.DatabaseFactory"/> object.</param>
    public RepositoryBase(IDatabaseFactory DbFactory)
    {
        DatabaseFactory = DbFactory;
    }

}
4

1 回答 1

0

您必须启用代理生成并将集合属性定义为虚拟才能使延迟加载正常工作。上下文也应该保持活力。

  public class CemexDb : DbContext
  {
     public CemexDb()
     {
        this.Configuration.ProxyCreationEnabled = true;
     } 

     public DbSet<Unicorn> Employees { get; set; }

  }
于 2013-06-05T12:42:07.233 回答