Free nHibernate: One-to-Many Communication

I have a one-to-many relationship problem. I have the following domain classes:

public class Installation : Entity<Installation>
{        
    public virtual string Name { get; set; }
    public virtual IList<Institution> Institutions { get; set; }

    public Installation()
    {
        Institutions = new List<Institution>();
    }
}
public class Institution : Entity
{
    public virtual string Name { get; set; }
    public virtual string Address { get; set; }
    public virtual string City { get; set; }
    public virtual Installation Installation { get; set; }        
}

I created an Entity base class according to the following post . I have the following mappings:

public class InstitutionMapping : ClassMap<Institution> 
{
    public InstitutionMapping()
    {
        WithTable("Institution");
        Id(i => i.Id).GeneratedBy.Guid();
        Map(i => i.Name).Not.Nullable().WithLengthOf(50);
        Map(i => i.Address).Not.Nullable().WithLengthOf(50);
        Map(i => i.City).Not.Nullable().WithLengthOf(50);
        References(i => i.Installation).ColumnName("InstallationId").Not.Nullable().WithForeignKey();
    }
}

public class InstallationMapping : ClassMap<Installation>
{
    public InstallationMapping()
    {
        WithTable("Installation");
        Id(i => i.Id).GeneratedBy.Guid();
        Map(i => i.Name).Not.Nullable().WithLengthOf(50);
        HasMany<Institution>(i => i.Institutions).KeyColumnNames.Add("InstallationId").Inverse().Cascade.All();
    }
}

I unit test add settings to the installation as follows:

Installation installation = TestHelper.CreateAnonymousInstallation();
installation.Institutions.Add(TestHelper.CreateAnonymousInstitution());
installation.Institutions.Add(TestHelper.CreateAnonymousInstitution());
session.Save(installation);    
session.Flush();
session.Clear();
Installation returnedInstallation = session.Get<Installation>(installation.Id);
Assert.AreEqual(2, returnedInstallation.Institutions.Count);

I get a statement exception because the returned number of institutions is 0. I checked in SQL Profiler and the institutions are stored in the database, but their InstallationId is null. Can someone tell me what I am doing wrong?

+3
source share
2 answers

inverse="false", , .

inverse="true", , .

inverse="true", , NHibernate . , NHibernate , , inverse="false" .

+5

, ,

Installation installation = TestHelper.CreateAnonymousInstallation();
Institution institution = TestHelper.CreateAnonymousInstitution();
institution.Installation = installation;
installation.Institutions.Add(institution);
+1

Source: https://habr.com/ru/post/1718183/


All Articles