NHibernate: mapping a one-to-many relationship to fill a collection without the use of a second class

StackOverflow https://stackoverflow.com/questions/19722274

سؤال

The database that I'm trying to map with NHibernate has a Plan table and a Date table. One plan can be associated with many dates, this is modelled by the Date table having a PLAN_ID foreign key column.

These are my current classes and mappings:

public class Plan
{
    public virtual int Id { get; set; }
    public virtual IList<PlanDate> Dates { get; set; }
}

public class PlanDate
{
    public virtual int Id { get; set; }

    public virtual int PlanId { get; set; }

    public virtual DateTime? Date { get; set; }
}

  <class name="Plan" table="PLAN">
    <id name="Id" unsaved-value="0">
      <column name="ID" not-null="true" />
      <generator class="native"/>
    </id>
    <bag name="Dates">
      <key column="PLAN_ID" />
      <one-to-many class="PlanDate" />
    </bag>
  </class>
  <class name="PlanDate" table="PLAN_DATE">
    <id name="Id" unsaved-value="0">
      <column name="ID" not-null="true" />
      <generator class="native"/>
    </id>
    <property name="Date" column="DATE" type="DateTime"/>
    <property name="PlanId" column="PLAN_ID" type="integer"/>
  </class>

This correctly fills the Dates collection in a Plan object with PlanDate objects. However, ideally I would like to have a collection of DateTime objects in the Plan class. I have no use for the PlanDate class other than for containing dates and I'm not going to update the data in the database. Example:

public class Plan
{
    public virtual int Id { get; set; }
    public virtual IList<DateTime> Dates { get; set; }
}

Is there any way to map to this class structure, and to get rid of the PlanDate class?

هل كانت مفيدة؟

المحلول

You can using this mapping:

<list name="Dates" table="PlanDates">
    <key column="PlanId"/>
    <index column="Position" />
    <element column="Value" type="System.DateTime"/>
</list>

The xml node <index column="Position" /> references the position of the element in the list.

And your class would exactly the way you wanted it:

public class Plan
{
    public Plan()
    {
        this.Dates = new List<DateTime>();
    }
    public virtual int Id { get; set; }
    public virtual IList<DateTime> Dates { get; set; }
}

You can find more info here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top