我正在尝试使用以下代码示例测试我的测试工具:
public void Test_tools()
{
// Arrange
DateTime appointmentDate = DateTime.Now;
DateTime appointmentDate2 = DateTime.Now - TimeSpan.FromDays(5);
DateTime appointmentDate3 = DateTime.Now - TimeSpan.FromDays(10);
string firstName = "Frank";
string lastName = "Carter";
DatabaseTools.AddPatientToDatabase(firstName, lastName,
appointmentDate, appointmentDate2, appointmentDate3);
var patients = DatabaseTools.GetPatientFromDatabase(firstName, lastName);
}
首先,我将 PatientEntity 与3个 AppointmentEntity 类添加到数据库中( AddPatientToDatabase 方法):
public static void AddPatientToDatabase(string firstName,
string lastName, params DateTime[] appointmentDate)
{
PatientEntity patient = new PatientEntity
{
FirstName = firstName,
LastName = lastName
};
foreach (DateTime item in appointmentDate)
{
var appointment = new AppointmentEntity
{
Date = item
};
patient.AddAppointment(appointment);
}
ISessionFactory sessionForTests =
NHibernateConfig.CreateSessionFactory(Database.TEST_DB_NAME);
using (ISession session = sessionForTests.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(patient);
transaction.Commit();
}
}
}
接下来,我尝试使用 GetPatientFromDatabase 方法使用FirstName和LastName条件从数据库中获取 PatientEntity ,如下所示:
public static IList<PatientEntity> GetPatientFromDatabase(string firstName, string lastName)
{
ISessionFactory sessionForTests =
NHibernateConfig.CreateSessionFactory(Database.TEST_DB_NAME);
using (ISession session = sessionForTests.OpenSession())
{
return session.QueryOver<PatientEntity>()
.Where(k => k.FirstName == firstName && k.LastName == lastName)
.Fetch(x => x.Appointments).Eager.List();
}
}
问题是,我收到了很多 PatientEntity 类,因为 AppointmentEntity 类是addes(而不是只有一个)。在3个结果中的每个结果中,患者具有相同的ID和约会集。在我设置的查询中,我的错误是什么?我正在使用PostgreSQL数据库,其中(使用pgAdmin)我看到,每个人都设置正确。问题是,如何在约会集合中查询只有一个 PatientEntity 和 AppointmentEntity 类。
修改
我还尝试使用 CreateCriteria ,但是一旦我设置了预约列表的热切提取,我得到3个相同的患者而不是1.可能是急切约会集合初始化中的错误?
public static IList<PatientEntity> GetPatientFromDatabase(string firstName, string lastName)
{
ISessionFactory sessionForTests = NHibernateConfig.CreateSessionFactory(Database.TEST_DB_NAME);
using (ISession session = sessionForTests.OpenSession())
{
return session.CreateCriteria<PatientEntity>()
.Add(Expression.Eq("FirstName", firstName))
.Add(Expression.Eq("LastName", lastName))
.SetFetchMode("Appointments", FetchMode.Eager)
.List<PatientEntity>();
}
}
答案 0 :(得分:0)
在@jdweng的帮助下,我能够提出另一个查询,它允许我在患者列表中获得初始化的约会集合而不重复:
public static IList<PatientEntity> GetPatientFromDatabase(string firstName,
string lastName)
{
ISessionFactory sessionForTests =
NHibernateConfig.CreateSessionFactory(Database.TEST_DB_NAME);
using (ISession session = sessionForTests.OpenSession())
{
return session.QueryOver<PatientEntity>()
.Where(k => k.FirstName == firstName && k.LastName == lastName)
.Fetch(x => x.Appointments).Eager
.TransformUsing(Transformers.DistinctRootEntity).List();
}
}