I have 2 classes that implment an interface.
The interface is passed into a method as a parameter, and subsequently used as the T class in the following NHibernate syntax
Session.Query<T>()
However, as the interface is implemented by 2 classes, the SQL that gets run by Session.Query is 2 Select statements (Select .. from Boy. and Select .. from Girl).
What I need to know is how to “convert” the IChild parameter into a Class, and then use that Class to populate the Session.Query() call.
The code is below. As you can see I have a workaround, but it’s not pretty and with multiple IChild classes will become a mass of duplicated code.
Thanks!
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;
}
Use generics: