Skip to content

Instantly share code, notes, and snippets.

@gmoothart
Created August 17, 2010 18:26
Show Gist options
  • Save gmoothart/531280 to your computer and use it in GitHub Desktop.
Save gmoothart/531280 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Mapping;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
namespace nhib_test
{
/*
* Model
*/
public class Order
{
public virtual int Id { get; set; }
public virtual string AccountName { get; set; }
public virtual IList<Product> Products { get; set; }
}
public class Product
{
public virtual int Id { get; set; }
public virtual string StatusReason { get; set; }
public virtual Order Order { get; set; }
}
/*
* Mapping
* */
class OrderMap: ClassMap<Order>
{
public OrderMap()
{
Id(x => x.Id);
Map(x => x.AccountName);
HasMany(x => x.Products)
.Inverse()
.Fetch.Subselect()
.Cascade.AllDeleteOrphan();
}
}
class ProductMap: ClassMap<Product>
{
public ProductMap()
{
Id(x => x.Id);
Map(x => x.StatusReason);
References(x => x.Order);
}
}
class Program
{
protected static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ShowSql()
.ConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=test_db;Integrated Security=SSPI;"))
.Mappings(m => m
.FluentMappings
.Add<OrderMap>()
.Add<ProductMap>())
.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true))
.BuildSessionFactory();
}
static void Main(string[] args)
{
var sf = CreateSessionFactory();
var sess = sf.OpenSession();
var qry = sess.CreateQuery(@"
select o from Order o")
.SetMaxResults(10);
var orders = qry.List<Order>();
// trigger lazy-loading of products by subselect fetch
Console.WriteLine(orders[0].Products[0].StatusReason);
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment