1: using System;
2: using FluentNHibernate.Automapping;
3: using FluentNHibernate.Cfg;
4: using FluentNHibernate.Cfg.Db;
5: using NHibernate;
6: using System.Linq;
7: using NHibernate.Cfg;
8: using NHibernate.Linq;
9: using NHibernate.Tool.hbm2ddl;
10:
11: namespace NHStart
12: {
13: public class Saver
14: {
15: public void Save(MyEntity entity)
16: {
17: using (var session = GetSession())
18: using(var tx = session.BeginTransaction())
19: {
20: session.Save(entity);
21:
22: tx.Commit();
23: }
24: }
25:
26: private ISession GetSession()
27: {
28: var sessionFactory = Factory;
29: return sessionFactory.OpenSession();
30: }
31:
32: protected ISessionFactory _Factory;
33: protected ISessionFactory Factory
34: {
35: get
36: {
37: if (_Factory == null)
38: {
39: Configuration config = null;
40:
41: _Factory =
42: Fluently
43: .Configure()
44: .Database(SQLiteConfiguration.Standard.ConnectionString(x => x.Is("Data Source=:memory:;Version=3;New=True;Pooling=True;Max Pool Size=1")))
45: .Mappings(x=>x.AutoMappings.Add(AutoMap
46: .Assemblies(new MyAutomappingConfiguration(), typeof(MyEntity).Assembly)))
47: .ExposeConfiguration(x=>config = x)
48: .BuildSessionFactory();
49:
50: using (var session = _Factory.OpenSession())
51: {
52: new SchemaExport(config).Execute(false, true, false, session.Connection, Console.Out);
53: }
54:
55: }
56: return _Factory;
57: }
58: }
59:
60: public MyEntity Load()
61: {
62: using (var session = GetSession())
63: using (var tx = session.BeginTransaction())
64: {
65: var item = session
66: .Linq<MyEntity>()
67: .First();
68:
69: tx.Commit();
70:
71: return item;
72: }
73: }
74: }
75:
76: public class MyAutomappingConfiguration : DefaultAutomappingConfiguration
77: {
78: public override bool ShouldMap(Type type)
79: {
80: return type.GetCustomAttributes(true).OfType<PersistedAttribute>().Any();
81: }
82: }
83:
84: [Persisted]
85: public class MyEntity
86: {
87: public virtual int Id { get; set; }
88: public virtual int Val { get; set; }
89: public virtual string Val2 { get; set; }
90: }
91:
92: public class PersistedAttribute : Attribute {}
93: }