开发者

Help trying to link two tables that share a common database column in nHibernate using HasOne

I'm using nHibernate on a webpage for viewing items from an already existing database. I'm having trouble linking two tables together. The two tables share a common column name that I need to cross reference. Granted, I would have designed the tables a little differently to just use a reference ID better but being this is a legacy database, I really need to figure out how to configure my Map to work on the existing schema.

I’m trying to use a HasOne relationship between two tables (I can also see how this could also fit into the ManyToOne) but I just can't seem to get anything to work with the right results...Having exhausted my Google cache I'm now hoping someone might be able to offer some quick insights to what I'm doing wrong.

The first table is called 'Report' which wants to load an object from another table called 'OperatingSystem'; Both share the common field ‘Report_Number’

The Model classes look like this:

  public class ReportModel
  {
    public virtual int Report_Number { get; set; }
    public virtual OperatingSystemsModel OperatingSystem { get; set; }
  }
  public class OperatingSystemsModel
  {
    public virtual string OS_Name { get; set; }
    public virtual int Report_Number { get; set; }
  }

*The important difference from the normal situation is that the two records are indexed via the Report_Number rather than the Report having an index into the Operating system.

The table mappings look like this:

public ReportMap()
{
  Table("pcd_PROBLEM40");
  Id(x => x.Report_Number).Column("Report_Number").GeneratedBy.Native();
  HasOne(x => x.OperatingSystem).PropertyRef(x => x.Report_Number).ForeignKey("Report_Number");
}
public OperatingSystemsMap()
{
  Table("pcd_os_names");
  Id(x => x.Report_Number).Column("Report_Number").GeneratedBy.Native();
  Map(x => x.OS_Name);
}

The goal being that the ReportModel’s OperatingSystem object will get populated correctly from the shared Report_number feild.

I’ve tried a variety of combinations of HasOne() with PropertyRef() and ForeignKey() but can’t seem to get one that works. I keep getting the following exception when I try to get a report.

{"Unknown column 'operatings2_.Report_Number' in 'field list'"}

public static ReportModel GetReport(int i_iReportNumber)
{
  ICriteria criteria = Session.CreateCriteria(typeof(ReportModel));
  criteria.Add(Restrictions.Eq("Report_Number", i_iReportNumber));
  return criteria.UniqueResult<ReportModel>();
}

Any insight开发者_如何学编程s would be much, much appreciated!


Try:

HasOne(x => x.OperatingSystem);

Or

HasOne(x => x.OperatingSystem).Constrained();

Also take a look at this post on brunoreis.com for more help on HasOne syntax:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜