我想我可能发现了一个错误,但我不确定。这可能是我的语法错误,但编译器没有捕捉到。无论如何,这就是我想要做的。基本上我已经编写了自己的存储库类,它基本上只是包装了 Fluent Repository 类。所以这里是相关的代码:
Public Class GenericRepository(Of T As IHasIntId)
Private _fluentRepos As FluentNHibernate.Framework.IRepository
Public Sub New(ByVal FluentRepository As
FluentNHibernate.Framework.IRepository)
_fluentRepos = FluentRepository
End Sub
Private Sub New()
End Sub
Public Function GetById(ByVal Id As Integer) As T
Return Query(Function(x As T) (x.Id = Id)).FirstOrDefault
End Function
Public Function Query(ByVal w As Expression(Of System.Func(Of T,
Boolean))) As IList(Of T)
Return _fluentRepos.Query(Of T)(w).ToList()
End Function
End Class
然后我编写了两个单元测试,一个将传递 InMemoryRepository,另一个将使用实际的 NHibernate 会话来访问真实的数据库。他们来了:
<TestMethod()> Public Sub InMemoryTest()
Dim inmemRepos As New InMemoryRepository()
Dim p As New Product()
Dim id As Integer = 5
p.Id = id
p.Title = "my product"
inmemRepos.Save(p)
Dim genRepos As New GenericRepository(Of Product)(inmemRepos)
Dim foundP = genRepos.GetById(id)
Assert.AreEqual(p.Title, foundP.Title)
End Sub
<TestMethod()> Public Sub DatabaseTest()
Dim session = NHibernateSessionManager.Instance.GetSession()
Dim flRepos As New Repository(session)
Dim genRepos As New GenericRepository(Of Product)(flRepos)
Dim id As Integer = 1
Dim p = genRepos.GetById(id)
Assert.IsNotNull(p)
Assert.AreEqual(id, p.Id)
End Sub
InMemoryTest 通过,DatabaseTest 失败。DatabaseTest 的例外是类型转换,从 int 到 product(或者可能相反)。不过,我能够“修复”它。在 Fluent NHibernate 代码中,我将 Repository 类的 Query 方法从:
return _session.Linq<T>().Where(where).ToArray();
到
return _session.Linq<T>().Where(where.Compile()).ToArray();
现在两个测试都通过了。Fluent NHibernate 项目中的所有单元测试都通过了任何一种方式。