NHibernate Many-to-Many Mapping

I am trying to display a legacy database here and I am facing a problem. In my schema, I have the concept of Modules and the concept of variables. Each module consists of one or more variables, and each of these variables has properties specific to that module. A Varable is attitude dependent.

Based on the classes below, the best way to map a ModuleVariable which looks to me like a many-to-many relationship with special properties is

Here are the classes:

public class Relation
{
    public virtual string RelationId
    {
        get;
        set;
    }
}

public class Variable
{
    public virtual string VariableId
    {
        get;
        set;
    }

    public virtual Relation RelationId
    {
        get;
        set;
    }
} 

public class Module
{
    public virtual string ModuleId
    {
        get;
        set;
    }
}

public class ModuleVariable
{       
    public virtual Module ModuleId
    {
        get;
        set;
    }

    public virtual Variable VariableId
    {
        get;
        set;
    }

    public virtual Relation RelationId
    {
        get;
        set;
    }

    public virtual Variable DownloadID
    {
        get;
        set;
    }

    public virtual Variable UploadID
    {
        get;
        set;
    }

    public string Repeatable
    {
        get;
        set;
    }
}

      

0


a source to share


2 answers


To have a many-to-many relationship with additional properties in such a relationship, you need to make ModuleVariable

a domain object and render it separate from Module

and Variable

.

Module

and Variable

will have a collection of objects ModuleVariable

, but ModuleVariable

will have a many-to-one link for the other two. Sort of:



<!-- Module mapping -->
<bag name="ModuleVariables" inverse="true">
    <key column="Module_id" />
    <one-to-many class="ModuleVariable" />
</bag>

<!-- ModuleVariable mapping -->
<many-to-one name="Module" column="Module_id" />

      

+2


a source


Many-to-many works only with a table with no additional properties. This is because many-to-many is a collection of elements within another object.

If there are no other columns in your ModuleVariable table, you can use this:

<bag name="Modules" table="MODULE_VARIABLE" cascade="save-update" lazy="true" >
  <key>
    <column name="Variable_Id" not-null="true"/>
  </key>
  <many-to-many class="Module">
    <column name="Module_Id" not-null="true"/>
  </many-to-many>
</bag>

      

And in your domain classes:



public IList Modules { get; set; }

      

And to use, you have to add modules:

variable.Modules.Add(module);

      

We hope to help.

0


a source







All Articles