我有這樣一個實體:延遲加載
public class Doctor : User
{
public Doctor(string userName, string firstName, string lastName,
string mobileNumber, string email, Sexes sex, Role myRole, DoctorExpertises expertise)
: base(userName, firstName, lastName, mobileNumber, email, sex, myRole)
{
this.Expertise = expertise;
this.Results = new List<Result>();
}
private Doctor()
{
this.Results = new List<Result>();
}
public void AddResult(Result result)
{
this.Results.Add(result);
}
public DoctorExpertises Expertise { get; private set; }
private ICollection<Result> results;
public virtual ICollection<Result> Results
{
get { return results; }
private set { results = value; }
}
}
,我有典型的資源庫,如:
public abstract class RepositoryBase<T> where T : class
{
private DbContext dataContext;
protected readonly IDbSet<T> dbset;
protected RepositoryBase(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
protected DbContext DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
public virtual void Add(T entity)
{
dbset.Add(entity);
}
public virtual void Update(T entity)
{
dbset.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
dbset.Remove(entity);
}
public virtual void Delete(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = dbset.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
dbset.Remove(obj);
}
public virtual T GetById(long id)
{
return dbset.Find(id);
}
public virtual T GetById(string id)
{
return dbset.Find(id);
}
public virtual IEnumerable<T> GetAll()
{
return dbset.ToList();
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return dbset.Where(where).ToList();
}
public T Get(Expression<Func<T, bool>> where)
{
return dbset.Where(where).FirstOrDefault<T>();
}
}
,我想偷懶負荷醫生用下面的測試結果之一代碼:
[TestMethod]
public void TestShouldLoadPropertyIfLazyLoaded()
{
// Act
Doctor doctor = this.userRepository.Get(u => u.UserName == "soroosh") as Doctor;
Result result = doctor.Results.FirstOrDefault();
// Asserts
Assert.IsNotNull(doctor);
Assert.IsNotNull(result);
}
不幸的是,它不能正常工作醫生不爲空,但結果爲空。
如果我使用include
方法加載正確,它會正確加載,但我希望使用延遲加載。
我看過this question以及其他類似的問題,但其中沒有一個是沒用的,因爲它們都使用急切的加載來解決問題。急於加載不適合我們,因爲在我的main problem似乎急於加載是不可能的。
我該怎麼辦?
對不起,但我不明白你說的是什麼。我再次說醫生不是零。謝謝:) –
好吧,我誤會了你 - 對不起;)我刪除了評論;)也許你可以嘗試以下內容: 結果結果= doctor.Results.ToList()。FirstOrDefault(); 順便說一句你應該conssider分裂成兩個單獨的測試;) –
哦,以及userRepository從哪裏來?你在關注數據庫嗎? –