I have a class (Project) that represents a somewhat large DB table. I need to retrieve only about a dozen columns, in addition to a sub-class (ProjectUses, which represents another DB table with a 1:1 relationship with Project). I am able to get the single columns of a Project object just fine using projections as seen below, but am having problems also retrieving an object of Project with the ProjectUses subclass populated. Can anyone please point me in the right direction?
Here is the repository code I am using:
public Project GetProjectDebenture(int pkProjectID)
{
var proj = _session.CreateCriteria(typeof(Project))
.SetProjection(Projections.ProjectionList()
.Add(Projections.Property("pkProjectID"), "pkProjectID")
.Add(Projections.Property("ReservePercentage"), "ReservePercentage")
.Add(Projections.Property("FundingFeePercentage"), "FundingFeePercentage")
.Add(Projections.Property("PackagingFeePercentage"), "PackagingFeePercentage")
)
.SetResultTransformer(Transformers.AliasToBean(typeof(Project)))
.Add(Restrictions.Eq("pkProjectID", pkProjectID))
.UniqueResult<Project>();
return proj;
}
return null;
}
I have tried using Projections.Property("ProjectUses")
and Projections.GroupProperty("ProjectUses")
to retrieve a populated subclass, but with no success.
And below is the [simplified] code for the class and mapping definitions
// Project class
public partial class Project
{
public int pkProjectID { get; set; }
public decimal ReservePercentage { get; set; }
public decimal FundingFeePercentage { get; set; }
public decimal PackagingFeePercentage { get; set; }
public ProjectUses ProjectUses { get; set; }
}
// ProjectUses class
public partial class ProjectUses
{
public int pkProjectID { get; set; }
public Project Project { get; set; }
...
}
// Project mapping
public class ProjectMap : ClassMap<Project>
{
public ProjectMap()
{
Table(@"Project");
LazyLoad();
Id(x => x.pkProjectID)
.Column("pkProjectID")
.Not.Nullable()
.GeneratedBy.Identity();
...
HasOne<ProjectUses>(x => x.ProjectUses)
.PropertyRef(r => r.Project)
.Cascade.All();
}
}
// Project Uses mapping
public class ProjectUsesMap : ClassMap<ProjectUses>
{
public ProjectUsesMap()
{
Table(@"ProjectUses");
LazyLoad();
Id(x => x.pkProjectID, "pkProjectID").GeneratedBy.Foreign("Project");
HasOne<Project>(x => x.Project)
.Constrained()
.ForeignKey()
.Cascade.None();
...
}
}
You could make a DTO with all the properties you need and project from Project
and ProjectUses
onto the new DTO. This has the additional advantage of separating the view model from the domain model.