### Install Gems Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Building Run this batch file to install necessary Ruby gems, including Bundler. ```batch InstallGems.bat ``` -------------------------------- ### Install Fluent NHibernate NuGet Package Source: https://github.com/nhibernate/fluent-nhibernate/blob/main/README.md Use this command to add the Fluent NHibernate NuGet package to your .NET project. ```bash dotnet add package FluentNHibernate ``` -------------------------------- ### Install Dependencies Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Building Use Bundler to download project dependencies like rake, mini_portile, rubyzip, and others. ```bash bundler install ``` -------------------------------- ### Initialize Auto-mapping for an Assembly Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Basic setup to integrate auto mappings for a given assembly. Ensure the StoreConfiguration is properly initialized. ```csharp var cfg = new StoreConfiguration(); AutoMap.AssemblyOf(cfg); ``` -------------------------------- ### Basic Fluent NHibernate Configuration Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-configuration Starts the configuration process, specifies database and mapping settings, optionally alters the configuration, and builds the SessionFactory. ```cs Fluently.Configure() .Database(/* your database settings */) .Mappings(/* your mappings */) .ExposeConfiguration(/* alter Configuration */) // optional .BuildSessionFactory(); ``` -------------------------------- ### Install Fluent NHibernate via NuGet Package Manager Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started This command installs the Fluent NHibernate package using the NuGet Package Manager Console. Ensure you have NuGet configured in your Visual Studio project. ```powershell PM> Install-Package FluentNHibernate ``` -------------------------------- ### Example Domain Model with Inheritance Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Automapping-inheritance Defines an abstract base class 'Entity' with an 'Id' property and two derived classes, 'Person' and 'Animal', demonstrating a common inheritance pattern. ```csharp namespace Entities { public abstract class Entity { public virtual int Id { get; set; } } public class Person : Entity { public virtual string FirstName { get; set; } public virtual string LastName { get; set; } } public class Animal : Entity { public virtual string Species { get; set; } } } ``` -------------------------------- ### Configure NHibernate with Automappings Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-configuration Use this configuration when only using automappings. Replace the placeholder with your specific automapping setup. ```cs var sessionFactory = Fluently.Configure() .Database(SQLiteConfiguration.Standard.InMemory) .Mappings(m => m.AutoMappings.Add( // your automapping setup here AutoMap.AssemblyOf(type => type.Namespace.EndsWith("Entities")))) .BuildSessionFactory(); ``` -------------------------------- ### MS SQL Server 2005 Connection String Examples Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Database-configuration Demonstrates different ways to set the connection string for MS SQL Server 2005 using Fluent NHibernate. ```csharp MsSqlConfiguration.MsSql2005 .ConnectionString("a raw string"); ``` ```csharp MsSqlConfiguration.MsSql2008 .ConnectionString(c => c .FromConnectionStringWithKey("connectionStringKey")); ``` ```csharp MsSqlConfiguration.MsSql2005 .ConnectionString(c => c .FromAppSetting("appSettingKey")); ``` ```csharp MsSqlConfiguration.MsSql2005 .ConnectionString(c => c .Server("my-server") .Database("database-name") .Username("jamesGregory") .Password("password1")); ``` -------------------------------- ### Car Entity Mapping with One-to-One Relationship Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Example mapping for a Car entity, including a one-to-one relationship to SteeringWheel using HasOne and PropertyRef. ```csharp public class CarMap : ClassMap { public CarMap() { Table( "Vehicles.dbo.Car" ); Id( x => x.CarId ); Map( x => x.Name ); Map( x => x.Year ); HasOne( x => x.SteeringWheel ).PropertyRef( x => x.Car); } } ``` -------------------------------- ### Example Fluent NHibernate Mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Conventions This is an example of a PersonMap class defining the structure of a Person entity using Fluent NHibernate's mapping API. ```csharp public class PersonMap : ClassMap { public PersonMap() { Id(x => x.Id); Map(x => x.Name) .Column("FullName") .Length(100); Map(x => x.Age); } } ``` -------------------------------- ### SteeringWheel Entity Mapping with One-to-One Relationship Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Example mapping for a SteeringWheel entity, including the inverse one-to-one relationship to Car using References and Unique. ```csharp public class SteeringWheelMap : ClassMap { public SteeringWheelMap() { Table( "Vehicles.dbo.SteeringWheel" ); Id( x => x.SteeringWheelId ); Map( x => x.Diameter ); Map( x => x.Color ); References( x => x.Car, "CarId" ).Unique(); } } ``` -------------------------------- ### Implement Conditional Convention Application Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Conventions Use IConventionAcceptance to specify criteria for when a convention should be applied. This example prevents the convention from applying to a specific type. ```csharp public class LowercaseTableNameConvention : IClassConvention, IConventionAcceptance { public void Accept(IAcceptanceCriteria criteria) { // alterations } /* snip */ } ``` ```csharp public void Accept(IAcceptanceCriteria criteria) { criteria.Expect(x => x.Type != typeof(SomeSpecialCase)); } ``` -------------------------------- ### Map Components Automatically with Fluent NHibernate Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Configure the automapper to recognize component types. This example shows how to identify the Address type as a component. ```csharp public override bool IsComponent(Type type) { return type == typeof(Address); } ``` -------------------------------- ### Define Domain Entities Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Example domain entities for a store, including Product and Shelf. The Product entity has an auto-incrementing primary key 'Id'. The Shelf entity contains a collection of Products, representing a one-to-many relationship. ```csharp public class Product { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual decimal Price { get; set; } } public class Shelf { public virtual int Id { get; set; } public virtual IList Products { get; set; } public Shelf() { Products = new List(); } } ``` -------------------------------- ### AttributePropertyConvention Example Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Available-conventions Use AttributePropertyConvention to apply conventions only to properties with a specific attribute. Subclass it and implement the Apply method. ```csharp public class ThereBeDragonsAttribute : Attribute {} public class ThereBeDragonsConvention : AttributePropertyConvention { protected override void Apply(ThereBeDragonsAttribute attribute, IPropertyInstance instance) { // do something to the instance } } ``` -------------------------------- ### Define a Class Convention for Table Naming Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Conventions Implement IClassConvention to define custom logic for class mappings. This example prefixes table names with 'tbl_'. ```csharp public class LowercaseTableNameConvention : IClassConvention { public void Apply(IClassInstance instance) { // alterations } } ``` ```csharp public void Apply(IClassInstance instance) { instance.Table("tbl_" + instance.EntityType.Name); } ``` -------------------------------- ### Define a generic base class Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto mapping generic base classes Example of an abstract generic base class where the Id type is determined by the generic argument. ```csharp public abstract class BaseEntity { public T Id { get; private set; } } ``` -------------------------------- ### Configure All Mapping Types: Fluent, Auto, and HBM Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-configuration This configuration is for advanced scenarios where you map entities using Fluent NHibernate, Auto-mapping, and traditional HBM mappings. Customize the automapping setup as needed. ```cs var sessionFactory = Fluently.Configure() .Database(SQLiteConfiguration.Standard.InMemory) .Mappings(m => { m.HbmMappings .AddFromAssemblyOf(); m.FluentMappings .AddFromAssemblyOf(); m.AutoMappings.Add( // your automapping setup here AutoMap.AssemblyOf(type => type.Namespace.EndsWith("Entities"))); }) .BuildSessionFactory(); ``` -------------------------------- ### Map One-to-Many Relationship with HasMany Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Use HasMany to map the 'one' side of a one-to-many relationship. This example maps an Author to a collection of Books. ```csharp public class Author { public IList Books { get; set; } } ``` ```csharp HasMany(x => x.Books); ``` -------------------------------- ### Map Collection with Private Backing Field Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Mapping-a-collection-that-uses-a-private-backing-field Use the Access property to map a collection property that is backed by a private field. This example shows mapping to a field named 'customers'. ```csharp public class Account { private IList customers = new List(); public IList Customers { get { return customers; } } } ``` ```csharp HasMany(x => x.Customers) .Access.CamelCaseField(); ``` -------------------------------- ### Specify Foreign Key in One-to-One Relationship Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Use PropertyRef to specify the foreign key when configuring a HasOne relationship. This example maps a Car to its SteeringWheel. ```csharp HasOne(x => x.SteeringWheel).PropertyRef(x => x.Car); ``` -------------------------------- ### Configure Inverse Side of One-to-One Relationship Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Use References with the .Unique() modifier to define the inverse side of a one-to-one relationship. This example maps the CarId foreign key for the SteeringWheel. ```csharp References(x => x.Car, "CarId").Unique(); ``` -------------------------------- ### Customize Component Column Naming Convention Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Override the GetComponentColumnPrefix method to customize how component property names are prefixed in database columns. This example prefixes with the component type name and an underscore. ```csharp public override string GetComponentColumnPrefix(Member member) { return member.PropertyType.Name + "_"; } ``` -------------------------------- ### Customize Identity Discovery in Auto-mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Override the IsId method to define custom logic for identifying primary key members. This example maps IDs named after their entity, like CustomerId. ```csharp public override bool IsId(Member member) { return member.Name == member.DeclaringType.Name + "Id"; } ``` -------------------------------- ### Basic Id Mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Map the Id property of an entity. Fluent NHibernate infers the generator type based on the property's return type (e.g., identity for int, Guid Comb for Guid). ```csharp Id(x => x.Id); ``` -------------------------------- ### Generate Release Notes Source: https://github.com/nhibernate/fluent-nhibernate/blob/main/ReleaseProcedure.md Run this command to generate release notes. Ensure you are in the project root. ```powershell .\build.ps1 --target Release-Notes ``` -------------------------------- ### Build and Test Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Building Execute the rake task to build the solution and run tests. Use 'rake -T' to view available tasks. ```bash rake ``` -------------------------------- ### Simulate OR Logic with Any Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Acceptance-criteria Use the Any method with multiple sub-acceptance criteria to apply conventions if any of the conditions are met. ```csharp criteria.Any( sub => sub.Expect(x => x.EntityType == typeof(Example)), sub => sub.Expect(x => x.TableName, Is.Not.Set), sub => sub.Expect(x => x.TableName == "tbl_Example")); ``` -------------------------------- ### Integrating Fluent NHibernate with Traditional Configuration Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Database-configuration Illustrates how to use Fluent NHibernate when NHibernate's traditional configuration is already in place. ```csharp var cfg = new NHibernate.Cfg.Configuration(); cfg.Configure(); // read config default style Fluently.Configure(cfg) .Mappings( m => m.FluentMappings.AddFromAssemblyOf())) .BuildSessionFactory(); ``` -------------------------------- ### Product Entity Class Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Represents a product with its name, price, and a list of stores stocking it. Initializes the StoresStockedIn collection in the constructor. ```csharp public class Product { public virtual int Id { get; protected set; } public virtual string Name { get; set; } public virtual double Price { get; set; } public virtual IList StoresStockedIn { get; protected set; } public Product() { StoresStockedIn = new List(); } } ``` -------------------------------- ### Export Fluent and Auto Mappings to HBM.xml Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-configuration This snippet demonstrates how to export your Fluent and Auto-mapped configurations into HBM.xml format to a specified directory. This is useful for generating or reviewing your mapping definitions. ```cs .Mappings(m => { m.FluentMappings .AddFromAssemblyOf() .ExportTo(@"C:\your\export\path"); m.AutoMappings .Add(/* ... */) .ExportTo(@"C:\your\export\path"); }) ``` -------------------------------- ### Initialize and Persist Data with Fluent NHibernate Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started This C# code snippet demonstrates the main application logic for initializing data, saving it to the database using a session factory, and then retrieving and displaying it. It includes creating Store, Product, and Employee entities and managing their relationships. ```csharp static void Main() { var sessionFactory = CreateSessionFactory(); using (var session = sessionFactory.OpenSession()) { using (var transaction = session.BeginTransaction()) { // create a couple of Stores each with some Products and Employees var barginBasin = new Store { Name = "Bargin Basin" }; var superMart = new Store { Name = "SuperMart" }; var potatoes = new Product { Name = "Potatoes", Price = 3.60 }; var fish = new Product { Name = "Fish", Price = 4.49 }; var milk = new Product { Name = "Milk", Price = 0.79 }; var bread = new Product { Name = "Bread", Price = 1.29 }; var cheese = new Product { Name = "Cheese", Price = 2.10 }; var waffles = new Product { Name = "Waffles", Price = 2.41 }; var daisy = new Employee { FirstName = "Daisy", LastName = "Harrison" }; var jack = new Employee { FirstName = "Jack", LastName = "Torrance" }; var sue = new Employee { FirstName = "Sue", LastName = "Walkters" }; var bill = new Employee { FirstName = "Bill", LastName = "Taft" }; var joan = new Employee { FirstName = "Joan", LastName = "Pope" }; // add products to the stores, there's some crossover in the products in each // store, because the store-product relationship is many-to-many AddProductsToStore(barginBasin, potatoes, fish, milk, bread, cheese); AddProductsToStore(superMart, bread, cheese, waffles); // add employees to the stores, this relationship is a one-to-many, so one // employee can only work at one store at a time AddEmployeesToStore(barginBasin, daisy, jack, sue); AddEmployeesToStore(superMart, bill, joan); // save both stores, this saves everything else via cascading session.SaveOrUpdate(barginBasin); session.SaveOrUpdate(superMart); transaction.Commit(); } // retreive all stores and display them using (session.BeginTransaction()) { var stores = session.CreateCriteria(typeof(Store)) .List(); foreach (var store in stores) { WriteStorePretty(store); } } Console.ReadKey(); } } ``` ```csharp public static void AddProductsToStore(Store store, params Product[] products) { foreach (var product in products) { store.AddProduct(product); } } ``` ```csharp public static void AddEmployeesToStore(Store store, params Employee[] employees) { foreach (var employee in employees) { store.AddEmployee(employee); } } ``` -------------------------------- ### Configure SQLite Standard in-memory Database Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Database-configuration Sets up a standard SQLite database to run entirely in memory. ```csharp SQLiteConfiguration.Standard .InMemory(); ``` -------------------------------- ### Define Product and Shelf Entities Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping These C# classes represent the domain entities that will be mapped. ```csharp public class Product { public int Id { get; set; } public virtual string Name { get; set; } public virtual decimal Price { get; set; } } public class Shelf { public virtual int Id { get; set; } public virtual IList Products { get; set; } public Shelf() { Products = new List(); } } ``` -------------------------------- ### Configure Auto-mapping with Multiple Conventions Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Sets up auto-mapping and adds multiple custom conventions for primary keys, foreign keys, and default string lengths. ```csharp AutoMap.AssemblyOf(cfg) .Conventions.Setup(c => { c.Add(); c.Add(); c.Add(); }); ``` -------------------------------- ### Adding Multiple Conventions in C# Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Conventions Shows how to add multiple conventions simultaneously using a params array in the .Conventions.Add() method. This allows for batch configuration of various mapping aspects. ```csharp .Conventions.Add( PrimaryKey.Name.Is(x => "ID"), DefaultLazy.Always(), ForeignKey.EndsWith("ID") ) ``` -------------------------------- ### Simple Global Conventions in C# Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Conventions These are basic conventions that can be applied globally to simplify mapping configurations. They cover aspects like table naming, primary key naming, and default access patterns. ```csharp Table.Is(x => x.EntityType.Name + "Table") PrimaryKey.Name.Is(x => "ID") AutoImport.Never() DefaultAccess.Field() DefaultCascade.All() DefaultLazy.Always() DynamicInsert.AlwaysTrue() DynamicUpdate.AlwaysTrue() OptimisticLock.Is(x => x.Dirty()) Cache.Is(x => x.AsReadOnly()) ForeignKey.EndsWith("ID") ``` -------------------------------- ### UserTypeConvention Example Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Available-conventions Use UserTypeConvention to automatically apply a specific IUserType to properties of a certain type. The convention targets properties whose type matches the IUserType's ReturnedType. ```csharp public class LatitudeUserType : IUserType { /* snip */ public Type ReturnedType { get { return typeof(Latitude); } } } public class LatitudeUserTypeConvention : UserTypeConvention {} ``` -------------------------------- ### Add Multiple Conventions to Configuration Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut Shows how to add multiple conventions simultaneously using a params array to the Fluent NHibernate configuration. ```csharp .Conventions.Add( PrimaryKey.Name.Is(x => "ID"), DefaultLazy.Always(), ForeignKey.EndsWith("ID") ) ``` -------------------------------- ### Basic Fluent NHibernate Configuration Structure Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Database-configuration This is the basic structure for configuring NHibernate using Fluent NHibernate, showing where database configuration fits in. ```csharp Fluently.Configure() .Database(/* examples here */) .Mappings(...) .BuildSessionFactory(); ``` -------------------------------- ### Configure SQLite Standard Database to Use a File Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Database-configuration Configures a standard SQLite database to use a specific file for storage. ```csharp SQLiteConfiguration.Standard .UsingFile("database.db"); ``` -------------------------------- ### Clone Fluent NHibernate Repository using Git Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started This command clones the Fluent NHibernate source code repository from GitHub. Use this if you plan to contribute or need the latest source code. ```bash git clone git://github.com/jagregory/fluent-nhibernate.git ``` -------------------------------- ### XML Mapping for Person and Animal Classes Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Automapping-inheritance Illustrates the traditional XML mapping configuration for 'Person' and 'Animal' entities, showing how their 'Id' and properties are defined. ```xml ``` -------------------------------- ### Configure Auto-mapping with Primary Key Convention Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Initializes auto-mapping for a given assembly and adds a custom convention for primary key naming. ```csharp var cfg = new StoreConfiguration(); AutoMap.AssemblyOf(cfg) .Conventions.Add(); ``` -------------------------------- ### Simulate OR Logic with Either Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Acceptance-criteria Use the Either method with two sub-acceptance criteria to apply conventions if either condition is met. ```csharp criteria.Either( sub => sub.Expect(x => x.EntityType == typeof(Example)), sub => sub.Expect(x => x.TableName, Is.Not.Set)); ``` -------------------------------- ### Implement IAutoMappingOverride Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Implement `IAutoMappingOverride` for a cleaner way to manage overrides for a specific entity. This is useful when you have many overrides. ```csharp public class PersonMappingOverride : IAutoMappingOverride { public void Override(AutoMapping mapping) { } } ``` -------------------------------- ### Build Session Factory with Fluent Configuration Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Database-configuration Builds an NHibernate SessionFactory using the Fluent NHibernate configuration API, including database settings and assembly mappings. ```csharp Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005 .ConnectionString(c => c .FromAppSetting("connectionString")) .ShowSql()) .Mappings(m => m .FluentMappings.AddFromAssemblyOf приложения())) .BuildSessionFactory(); ``` -------------------------------- ### Create Session Factory with Schema Generation Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started This snippet demonstrates how to configure Fluent NHibernate to expose the NHibernate Configuration object and use it to build the database schema. It includes deleting the existing database file before creating a new one. ```csharp private static ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database( SQLiteConfiguration.Standard .UsingFile("firstProject.db") ) .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) .ExposeConfiguration(BuildSchema) .BuildSessionFactory(); } private static void BuildSchema(Configuration config) { // delete the existing db on each run if (File.Exists(DbFile)) File.Delete(DbFile); // this NHibernate tool takes a configuration (with mapping info in) // and exports a database schema from it new SchemaExport(config) .Create(false, true); } ``` -------------------------------- ### Enable Dynamic Insert Shortcut Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut A shortcut to always generate dynamic INSERT statements. ```csharp DynamicInsert.AlwaysTrue() ``` -------------------------------- ### Create NHibernate SessionFactory Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Initializes an NHibernate ISessionFactory. This is a basic structure before any configuration is applied. ```csharp private static ISessionFactory CreateSessionFactory() { } ``` -------------------------------- ### Final Schema with Custom Conventions Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Displays the database schema after applying all custom conventions for primary keys, foreign keys, and string lengths. ```sql table Product ( ProductId int identity primary key, Name varchar(250), Price decimal, Shelf_FK int foreign key ) table Shelf ( ShelfId int identity primary key ) ``` -------------------------------- ### Add Conventions from Assembly Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Conventions Inform Fluent NHibernate to use all conventions defined within a specific assembly. This is done during the fluent mapping configuration. ```csharp Fluently.Configure() .Database(/* database config */) .Mappings(m => { m.FluentMappings .AddFromAssemblyOf() .Conventions.AddFromAssemblyOf(); }) ``` -------------------------------- ### Default Schema Mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Illustrates the database schema generated by Fluent NHibernate's default conventions for the Product and Shelf entities. ```sql table Product ( Id int identity primary key, Name varchar(100), Price decimal, Shelf_id int foreign key ) table Shelf ( Id int identity primary key ) ``` -------------------------------- ### Configure Cache Shortcut Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut A shortcut to configure caching for entities, specifically as read-only. ```csharp Cache.Is(x => x.AsReadOnly()) ``` -------------------------------- ### Enable Dynamic Update Shortcut Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut A shortcut to always generate dynamic UPDATE statements. ```csharp DynamicUpdate.AlwaysTrue() ``` -------------------------------- ### MS SQL Server 2005 Specific Options Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Database-configuration Shows how to apply specific options like UseOuterJoin and DefaultSchema for MS SQL Server 2005 configuration. ```csharp MsSqlConfiguration.MsSql2005 .UseOuterJoin() .DefaultSchema("dbo"); ``` -------------------------------- ### Employee Mapping Test with Custom Reference Comparison Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Persistence-specification-testing Tests the Employee mapping with a Store reference using a custom equality comparer to verify the correct Store was loaded. Ensure the session object and a CustomEqualityComparer are available. ```csharp [Test] public void CanCorrectlyMapEmployee() { new PersistenceSpecification(session, new CustomEqualityComparer()) .CheckProperty(c => c.Id, 1) .CheckProperty(c => c.FirstName, "John") .CheckProperty(c => c.LastName, "Doe") .CheckReference(c => c.Store, new Store() {Name = "MyStore"}) .VerifyTheMappings(); } ``` -------------------------------- ### Store Entity Class with Relationship Helpers Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Represents a store with its name, products, and staff. Includes helper methods AddProduct and AddEmployee to manage bidirectional relationships, ensuring both sides are set for NHibernate. ```csharp public class Store { public virtual int Id { get; protected set; } public virtual string Name { get; set; } public virtual IList Products { get; set; } public virtual IList Staff { get; set; } public Store() { Products = new List(); Staff = new List(); } public virtual void AddProduct(Product product) { product.StoresStockedIn.Add(this); Products.Add(product); } public virtual void AddEmployee(Employee employee) { employee.Store = this; Staff.Add(employee); } } ``` -------------------------------- ### Create SQLite Session Factory from Web.config Connection String Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Database-configuration Creates an NHibernate SessionFactory for SQLite, reading the connection string from the web.config file and mapping entities from the current assembly. ```csharp public static class MySQLiteSessionFactory { public static ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database( SQLiteConfiguration.Standard.ConnectionString( c => c.FromConnectionStringWithKey("MyConnectionString"))) .Mappings(x => x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())) .BuildSessionFactory(); } } ``` -------------------------------- ### Basic ClassMap Declaration Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Derive from `ClassMap` to create a mapping for your entity. Mappings are defined within the constructor. ```csharp public class PersonMap : ClassMap { public PersonMap() { } } ``` -------------------------------- ### Configure Auto-mapping with Custom Configuration Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Pass an instance of your custom `IAutomappingConfiguration` to the `AutoMap.AssemblyOf` method when setting up Fluent NHibernate mappings. ```csharp var cfg = new StoreConfiguration(); var sessionFactory = Fluently.Configure() .Database(/* database config */) .Mappings(m => m.AutoMappings.Add( AutoMap.AssemblyOf(cfg)) .BuildSessionFactory(); ``` -------------------------------- ### Check if Any Item Matches Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Acceptance-criteria Use the IsAny extension method to check if the current item is equal to any of the provided items in a params array. ```csharp // Example usage for IsAny (not explicitly shown in source, but implied by description) ``` -------------------------------- ### Configure Mixed HBM and Fluent Mappings Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-configuration Use this configuration when migrating entities to Fluent NHibernate, allowing both HBM and Fluent mappings to coexist. Ensure YourEntity is defined in the specified assemblies. ```cs var sessionFactory = Fluently.Configure() .Database(SQLiteConfiguration.Standard.InMemory) .Mappings(m => { m.HbmMappings .AddFromAssemblyOf(); m.FluentMappings .AddFromAssemblyOf(); }) .BuildSessionFactory(); ``` -------------------------------- ### Configure One-to-One Relationship Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Use HasOne for one-to-one relationships, typically a less common scenario than many-to-one. Ensure to use .Unique() on the inverse side if using References. ```csharp HasOne(x => x.Cover); ``` -------------------------------- ### Chain Expectations with AND Logic Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Acceptance-criteria Chain multiple Expect calls to create a combined condition where all expectations must be met. ```csharp criteria .Expect(x => x.EntityType == typeof(Example)) .Expect(x => x.TableName, Is.Not.Set); ``` -------------------------------- ### Add Single Convention to Configuration Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut Demonstrates how to add a single convention, PrimaryKey.Name.Is(x => "ID"), to the Fluent NHibernate configuration. ```csharp Fluently.Configure() .Database(/* database config */) .Mappings(m => { m.FluentMappings .AddFromAssemblyOf() .Conventions.Add(PrimaryKey.Name.Is(x => "ID")); }) ``` -------------------------------- ### Product Entity Mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Maps the 'Id', 'Name', and 'Price' properties of a Product entity. It configures a many-to-many relationship with the 'Store' entity, specifying the join table and using 'Inverse' and 'Cascade.All' for relationship management. ```csharp public class ProductMap : ClassMap { public ProductMap() { Id(x => x.Id); Map(x => x.Name); Map(x => x.Price); HasManyToMany(x => x.StoresStockedIn) .Cascade.All() .Inverse() .Table("StoreProduct"); } } ``` -------------------------------- ### Fluent NHibernate Equivalent for Cat Class Mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started This C# code demonstrates the Fluent NHibernate mapping for the 'Cat' class, providing a more concise and code-based alternative to HBM XML. It maps properties, references, and collections. ```csharp public class CatMap : ClassMap { public CatMap() { Id(x => x.Id); Map(x => x.Name) .Length(16) .Not.Nullable(); Map(x => x.Sex); References(x => x.Mate); HasMany(x => x.Kittens); } } ``` -------------------------------- ### Map Collection with Private Backing Field and Prefix Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Mapping-a-collection-that-uses-a-private-backing-field Use the Access property with a prefix overload to map a collection property backed by a private field with a specific naming convention, like a leading underscore. ```csharp HasMany(x => x.Customers) .Access.CamelCaseField(Prefix.Underscore); ``` -------------------------------- ### Updated Schema with Custom Primary Key Naming Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Shows the resulting database schema after applying the PrimaryKeyConvention. ```sql table Product ( ProductId int identity primary key, Name varchar(100), Price decimal, Shelf_id int foreign key ) table Shelf ( ShelfId int identity primary key ) ``` -------------------------------- ### Set Table Name Shortcut Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut A concise shortcut to set the table name based on the entity type's name, appending 'Table'. ```csharp Table.Is(x => x.EntityType.Name + "Table") ``` -------------------------------- ### Configure SessionFactory with Auto Mappings Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Integrate auto-mapping into NHibernate configuration using the Fluently.Configure API. The AutoMappings.Add(AutoMap.AssemblyOf()) call tells Fluent NHibernate to use the auto-mapper for discovering and applying entity mappings. ```csharp var sessionFactory = Fluently.Configure() .Database(/* database config */) .Mappings(m => m.AutoMappings .Add(AutoMap.AssemblyOf())) .BuildSessionFactory(); ``` -------------------------------- ### Set Default Lazy Loading Shortcut Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut A shortcut to enable default lazy loading for all properties. ```csharp DefaultLazy.Always() ``` -------------------------------- ### Configure SessionFactory with Mappings Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Completes the ISessionFactory configuration by adding Fluent NHibernate mappings from a specified assembly. This requires that your mappings are correctly defined within the Program class's assembly. ```csharp private static ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database( SQLiteConfiguration.Standard .UsingFile("firstProject.db") ) .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) .BuildSessionFactory(); } ``` -------------------------------- ### Configure SessionFactory with Fluent NHibernate Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Configures an ISessionFactory using Fluent NHibernate's Fluently.Configure API. This version builds the session factory without specific database or mapping configurations. ```csharp private static ISessionFactory CreateSessionFactory() { return Fluently.Configure() .BuildSessionFactory(); } ``` -------------------------------- ### Use ComponentMap in CompanyMap Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping This C# code shows how to use the defined AddressMap within a CompanyMap by simply calling Component(x => x.Address). ```csharp public CompanyMap() { Component(x => x.Address); } ``` -------------------------------- ### Basic Employee Entity Mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Defines the base mapping class for an Employee entity, deriving from ClassMap. ```csharp public class EmployeeMap : ClassMap { } ``` -------------------------------- ### Use Overrides from Assembly Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Instruct the `AutoPersistenceModel` to discover and use `IAutoMappingOverride` implementations from a specified assembly. ```csharp AutoMap.AssemblyOf(cfg) .UseOverridesFromAssemblyOf(); ``` -------------------------------- ### Implement Custom Foreign Key Convention Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Custom convention to name foreign key columns with a '_FK' suffix. It handles cases where the property might be null. ```csharp public class CustomForeignKeyConvention : ForeignKeyConvention { protected override string GetKeyName(PropertyInfo property, Type type) { if (property == null) return type.Name + "_FK"; return property.Name + "_FK"; } } ``` -------------------------------- ### Check Collection is Empty Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Acceptance-criteria Use the IsEmpty extension method for collections, equivalent to checking if collection.Count() == 0. ```csharp // Example usage for IsEmpty (not explicitly shown in source, but implied by description) ``` -------------------------------- ### Inline component mapping for Address in CompanyMap Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping This C# code demonstrates an inline component mapping for the Address property within a CompanyMap. This approach is redundant if the component is used in multiple entities. ```csharp public CompanyMap() { Component(x => x.Address, m => { m.Map(x => x.Number); m.Map(x => x.Street); m.Map(x => x.City); m.Map(x => x.PostCode); }); } ``` -------------------------------- ### Set Default Access Shortcut Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut A shortcut to set the default property access strategy to use fields. ```csharp DefaultAccess.Field() ``` -------------------------------- ### Apply Class and Id Conventions Always Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Conventions Use ConventionBuilder.Class.Always and ConventionBuilder.Id.Always to apply conventions to all mapping instances of their respective types. ```csharp ConventionBuilder.Class.Always(x => x.Table(x.EntityType.Name.ToLower())) ``` ```csharp ConventionBuilder.Id.Always(x => x.Column("ID")) ``` -------------------------------- ### Employee Mapping with Store Reference Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Persistence-specification-testing Defines an Employee mapping that includes a reference to a Store entity. This requires custom equality comparison for the reference. ```csharp public class EmployeeMap : ClassMap { public EmployeeMap() { Id(x => x.Id); Map(x => x.FirstName); Map(x => x.LastName); References(x => x.Store); } } ``` -------------------------------- ### Basic Employee Mapping Test Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Persistence-specification-testing Tests the basic mapping of the Employee entity using PersistenceSpecification. Ensure the session object is available in the test context. ```csharp using FluentNHibernate.Testing; [Test] public void CanCorrectlyMapEmployee() { new PersistenceSpecification(session) .CheckProperty(c => c.Id, 1) .CheckProperty(c => c.FirstName, "John") .CheckProperty(c => c.LastName, "Doe") .VerifyTheMappings(); } ``` -------------------------------- ### Custom Equality Comparer for Store Objects Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Persistence-specification-testing Provides a custom IEqualityComparer implementation to compare Store objects based on their Id property. This is necessary when the default Object.Equals() is insufficient. ```csharp public class CustomEqualityComparer: IEqualityComparer { public bool Equals(object x, object y) { if (x == null || y == null) { return false; } if (x is Store && y is Store) { return ((Store) x).Id == ((Store) y).Id; } return x.Equals(y); } public int GetHashCode(object obj) { throw new NotImplementedException(); } } ``` -------------------------------- ### Subclass Mapping - Table-per-class-hierarchy Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Maps multiple subclasses to a single table using a discriminator column. The discriminator column identifies the specific subclass for each row. This strategy requires specifying the discriminator column in the parent's ClassMap. ```csharp public class ParentMap : ClassMap { public ParentMap() { Id(x => x.Id); Map(x => x.Name); DiscriminateSubClassesOnColumn("type"); } } public class ChildMap : SubclassMap { public ChildMap() { DiscriminatorValue(valueRepresentingThisSubclass); Map(x => x.AnotherProperty); } } ``` -------------------------------- ### Set Default Cascade Shortcut Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut A shortcut to set the default cascade strategy for associations to 'All'. ```csharp DefaultCascade.All() ``` -------------------------------- ### Ignore Multiple Properties Globally Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Use `OverrideAll` with multiple string arguments to ignore several properties by name across all entities. ```csharp .OverrideAll(map => { map.IgnoreProperties("YourProperty", "AnotherProperty"); }); ``` -------------------------------- ### Use ComponentMap in PersonMap Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping This C# code shows how to use the defined AddressMap within a PersonMap by simply calling Component(x => x.Address). ```csharp public PersonMap() { Component(x => x.Address); } ``` -------------------------------- ### Complete Employee Entity Mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Maps the 'Id', 'FirstName', 'LastName' properties and establishes a many-to-one relationship with the 'Store' entity for an Employee. ```csharp public class EmployeeMap : ClassMap { public EmployeeMap() { Id(x => x.Id); Map(x => x.FirstName); Map(x => x.LastName); References(x => x.Store); } } ``` -------------------------------- ### Set Foreign Key Naming Convention Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut A shortcut to set a convention for foreign key column names, ending with 'ID'. ```csharp ForeignKey.EndsWith("ID") ``` -------------------------------- ### Basic Property Mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Use the `Map` method to map a property. Fluent NHibernate infers the column name and type from the property itself. ```csharp Map(x => x.FirstName); ``` -------------------------------- ### Implement Default String Length Convention Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Auto-mapping Custom convention to set the default length for string properties to 250 characters. ```csharp public class DefaultStringLengthConvention : IPropertyConvention { public void Apply(IPropertyInstance instance) { instance.Length(250); } } ``` -------------------------------- ### Set Optimistic Lock Shortcut Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut A shortcut to configure optimistic locking based on whether the property is dirty. ```csharp OptimisticLock.Is(x => x.Dirty()) ``` -------------------------------- ### Store Entity Mapping Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Maps the 'Id' and 'Name' properties of a Store entity. It also defines one-to-many ('HasMany') and many-to-many ('HasManyToMany') relationships with Employee and Product entities, respectively, using method chaining for configuration. ```csharp public class StoreMap : ClassMap { public StoreMap() { Id(x => x.Id); Map(x => x.Name); HasMany(x => x.Staff) .Inverse() .Cascade.All(); HasManyToMany(x => x.Products) .Cascade.All() .Table("StoreProduct"); } } ``` -------------------------------- ### Inline component mapping for Address in PersonMap Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping This C# code demonstrates an inline component mapping for the Address property within a PersonMap. This approach is redundant if the component is used in multiple entities. ```csharp public PersonMap() { Component(x => x.Address, m => { m.Map(x => x.Number); m.Map(x => x.Street); m.Map(x => x.City); m.Map(x => x.PostCode); }); } ``` -------------------------------- ### Configure SessionFactory with SQLite Database Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Getting-started Configures an ISessionFactory with Fluent NHibernate, specifying a file-based SQLite database connection. Ensure the database file is created or accessible. ```csharp private static ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database( SQLiteConfiguration.Standard .UsingFile("firstProject.db") ) .BuildSessionFactory(); } ``` -------------------------------- ### Entity with an Address component Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping This C# code shows how an entity (Person) can include the Address component. ```csharp public class Person { public Address Address { get; set; } } ``` -------------------------------- ### Set Default Schema for Application Configuration Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Using-multiple-or-different-schemas Configure the default schema for all entities in your application using the DefaultSchema method on your DatabaseConfiguration. This can potentially improve query performance. ```csharp MsSqlServerConfiguration.MsSql2005 .DefaultSchema("dbo"); ``` -------------------------------- ### Check Collection is Not Empty Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Acceptance-criteria Use the IsNotEmpty extension method for collections, equivalent to checking if collection.Count() > 0. ```csharp // Example usage for IsNotEmpty (not explicitly shown in source, but implied by description) ``` -------------------------------- ### Apply Class Convention Always Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut Applies a table naming convention to all class mappings. The table name is derived from the entity type's name in lowercase. ```csharp ConventionBuilder.Class.Always(x => x.Table(x.EntityType.Name.ToLower())) ``` -------------------------------- ### Define a reusable ComponentMap for Address Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping This C# code defines a reusable ComponentMap for the Address class, centralizing its mapping logic. ```csharp public class AddressMap : ComponentMap
{ public AddressMap() { Map(x => x.Number); Map(x => x.Street); Map(x => x.City); Map(x => x.PostCode); } } ``` -------------------------------- ### Configure NHibernate with Mixed Mappings Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-configuration This configuration is for scenarios combining standard fluent mappings and automappings. The Mappings method can accept multiple mapping types. ```cs var sessionFactory = Fluently.Configure() .Database(SQLiteConfiguration.Standard.InMemory) .Mappings(m => { m.FluentMappings .AddFromAssemblyOf(); m.AutoMappings.Add( // your automapping setup here AutoMap.AssemblyOf(type => type.Namespace.EndsWith("Entities"))); }) .BuildSessionFactory(); ``` -------------------------------- ### Apply Id Convention Always Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Convention-shortcut Sets the column name for all ID mappings to 'ID'. This is a simple catch-all for ID column naming. ```csharp ConventionBuilder.Id.Always(x => x.Column("ID")) ``` -------------------------------- ### Another entity with an Address component Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping This C# code shows how another entity (Company) can also include the Address component. ```csharp public class Company { public Address Address { get; set; } } ``` -------------------------------- ### Configure MS SQL 2005 Connection Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Database-configuration Configures an MS SQL 2005 database connection using the connection string from application settings and enables SQL logging. ```csharp MsSqlConfiguration.MsSql2005 .ConnectionString(c => c .FromAppSetting("connectionString")) .ShowSql(); ``` -------------------------------- ### Mapping Private Property with Reveal.Member Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Mapping-private-properties Use `Reveal.Member(string memberName)` to map private or protected properties by their string name. This avoids modifying the entity but can be prone to renaming issues. ```csharp public class Product { private int Id { get; set; } } public ProductMap : ClassMap { public ProductMap() { Id(Reveal.Member("Id")); } } ``` -------------------------------- ### Configure 'Any' Mapping in Fluent NHibernate Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Fluent-mapping Use this to map polymorphic associations. Specify the entity type column, identifier column, and the identifier's type. ```csharp ReferencesAny(x => x.Author) .EntityTypeColumn("Type") .EntityIdentifierColumn("Id") .IdentityType(); ``` -------------------------------- ### Automap byte[] Version Columns as Timestamp Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Release-notes-1.0RTM Configures byte array version columns to be automatically mapped as SQL timestamp properties. This follows a common pattern for handling optimistic concurrency. ```csharp byte[] version columns are now automapped as sql timestamp properties ``` -------------------------------- ### Apply Class Convention Conditionally Source: https://github.com/nhibernate/fluent-nhibernate/wiki/Conventions Use ConventionBuilder.Class.When to apply a convention only when a specified condition is met. The first parameter is the condition, and the second is the action to perform if the condition is true. ```csharp ConventionBuilder.Class.When( c => c.Expect(x.TableName, Is.Not.Set), // when this is true x => x.Table(x.EntityType.Name + "Table") // do this ) ```