[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 =&gt; 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;
}
}
答案 0 :(得分:0)
您必须启用代理生成,并将集合属性定义为虚拟,以便延迟加载工作。 上下文也应该保持活力。
public class CemexDb : DbContext
{
public CemexDb()
{
this.Configuration.ProxyCreationEnabled = true;
}
public DbSet<Unicorn> Employees { get; set; }
}