我有2個類實現接口。 接口被傳遞到一個方法作爲參數,並隨後在下面的NHibernate語法用作T艙從接口中查找實現的類
Session.Query<T>()
然而,由於界面由2類,即得到由會話運行SQL實現。查詢是2個選擇語句(Select .. from Boy。和Select .. from Girl)。
我需要知道的是如何將IChild參數「轉換」爲類,然後使用該類來填充Session.Query()調用。
代碼如下。正如你可以看到我有一個解決方法,但它不是很漂亮,並且多個IChild類將成爲大量的重複代碼。
謝謝!
public interface IChild
{
DateTime Date { get; }
Parent Parent { get; set; }
}
public class Boy : IChild
{
public virtual Parent Parent { get; set; }
public virtual DateTime GraduationDate { get; set; }
public virtual DateTime Date { get { return GraduationDate; } set { } }
}
public class Girl : IChild
{
public virtual Parent Parent { get; set; }
public virtual DateTime WeddingDate { get; set; }
public virtual DateTime Date { get { return WeddingDate; } set { } }
}
public bool Create(IChild entity)
{
//Is there an existing child record for the key details
IChild child = null;
if(entity is Boy)
{
child = Session.Query<Boy>()
.Where(x => x.Date == entity.Date)
.SingleOrDefault();
}
else if (entity is Girl)
{
child = Session.Query<Girl>()
.Where(x => x.Date == entity.Date)
.SingleOrDefault();
}
return child.Parent != null;
}
謝謝Piotr - 完美。 –