Nhibernate helpers
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; }
}
Mapping
namespace RealWebDevelopers;
public static partial class Extensions
{
public static IServiceCollection AddNHibernate(this IServiceCollection services)
{
services.AddSingleton(factory =>
{
// ...
return Fluently
.Configure()
.Database(MySQLConfiguration.Standard
.ConnectionString(options.ConnectionString)
.ShowSql())
.Mappings(mappings => mappings.AutoMappings.Add(AutoMap.AssemblyOf()
.Where(where => where.Namespace!.Equals("TradingApplication.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");
})
// ...
});
}
}
See associated posts: Service collection Fluent Nhibernate