Real Web Developers

Nhibernate cheat sheet

Parent and child

Models


namespace RealWebDevelopers.Models;

public class Parent
{
    public virtual required string Reference { get; set; }
    public virtual required string Name { get; set; }
    public virtual required ISet<Child> Children { get; set; } = new HashSet<Child>();
}

public class Child
{
    public virtual required string Reference { get; set; }
    public virtual required string Name { get; set; }
    public virtual required Parent Parent { get; set; }
}
    

Dependency injection

namespace RealWebDevelopers;
public static partial class Extensions
{
    public static IServiceCollection AddNHibernate(this IServiceCollection services, AutoPersistenceModel autoPersistenceModel)
    {
        services.AddSingleton(factory =>
        {
            // ...
            return Fluently
                .Configure()
                .Database(MySQLConfiguration.Standard
                    .ConnectionString(options.ConnectionString)
                    .ShowSql())
                .Mappings(mappings => mappings.AutoMappings.Add(autoPersistenceModel))
            // ...
        });
    }
}
    

Mappings (Program.cs)

namespace RealWebDevelopers;

using Microsoft.Extensions.Options;

public class Program
{
    public static void Main(string[] args)
    {
        // boiler plate web application
        builder.Services.AddOptions<NHibernateOptions>().Bind(builder.Configuration.GetSection("NHibernateOptions"));
        var mappings = AutoMap.AssemblyOf()
            .Where(where => where.Namespace!.Equals("RealWebDevelopers.Models", StringComparison.OrdinalIgnoreCase))
            .Override(populateMap =>
            {
                populateMap.Id(memberExpression => memberExpression.Reference).Not.Nullable().Length(31).GeneratedBy.Assigned();

                // The next line sets this as the parent.
                // Note the KeyColumn is the name of the column on the Child entity which holds a reference to this Parent
                populateMap.HasMany(memberExpression => memberExpression.Children)
                    .Cascade.AllDeleteOrphan()
                    .Inverse()
                    .KeyColumn("ParentReference");
            })
            .Override(populateMap =>
            {
                populateMap.Id(memberExpression => memberExpression.Reference).Not.Nullable().Length(31).GeneratedBy.Assigned();
                populateMap.References(memberExpression => memberExpression.Parent).Column("ParentReference");
            });
        builder.Services.AddNHibernate(mappings);

        // etc.
    }
}

See associated posts: Service collection Fluent Nhibernate