[英]Generic Repository with Related Entities
我有一個像這樣的通用存儲庫:
public interface IGenericRepository<TObject> where TObject : class
{
TObject Add(TObject t);
}
public class GenericRepository<TObject> : IGenericRepository<TObject> where TObject : class
{
private readonly DbContext context;
public GenericRepository(DbContext context)
{
this.context = context;
}
public virtual TObject Add(TObject t)
{
context.Set<TObject>().Add(t);
context.SaveChanges();
return t;
}
}
在我的EF模型中,我有作者和書籍,它們之間具有1:N的關系。 作者具有導航屬性“ Books”至Book,而Book具有“作者” Author。
然后我有一個通用的服務是這樣的:
public class GenericService<TObject> : IGenericService<TObject> where TObject : class
{
private readonly IGenericRepository<TObject> context;
public GenericService(IGenericRepository<TObject> ct)
{
context = ct;
}
public TObject Add(TObject data)
{
return context.Add(data);
}
}
我有這樣的單元測試:
[TestMethod]
public void TestAdd()
{
var b = new Book();
b.AuthorId = 1;
b.Name = "Test";
b.ISBN = "1111";
var service = new GenericService(new GenericRepository<Book>(new MyDbEntities()));
var newBook = service.Add(b);
Assert.AreEqual("Author1", newBook.Author.Name);
}
問題是newBook.Author為null,這意味着通過Add方法新創建的對象沒有任何相關實體。 我知道針對此類問題的解決方案之一是使用.include()包含所有相關實體,但就我而言,這是一個通用存儲庫,我不知道如何實現。
任何幫助,將不勝感激。
您的問題是如何實例化Book對象。 代替
var b = new Book();
你應該做類似的事情
var b = service.Create();
其中Create是應通過EF返回新書的方法:
context.Set<TObject>().Create();
使用create時,EF將返回一個代理對象,因此,在將導航屬性附加到上下文之后,假定您所有引用均正常並且您的DatabaseContext使用延遲加載,則將加載導航屬性。
檢查: https : //stackoverflow.com/a/31406426/1270813
順便說一下,驗證延遲加載功能的單元測試的原因是什么? 只是為了學習嗎? 根據經驗,您應該測試您的代碼,而不是其他框架。
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.