Thank you, Fran.  Looks good. I'll have to go read the fine manual to find 
out what the Configure.SetInterceptor does, that's not something I've seen 
yet.  Thank you again.  :-) 

On Thursday, June 26, 2014 8:28:19 PM UTC-5, fknebels wrote:
>
> Here's an NHibernateInitializer class I use with mapping by code,
>
> It should take care of everything you need.
>
> using NHibernate.Cfg;
> using NHibernate.Cfg.MappingSchema;
> using NHibernate.Dialect;
> using NHibernate.Driver;
> using NHibernate.Event;
> using NHibernate.Extensions.Domain;
> using NHibernate.Extensions.EventListeners;
> using NHibernate.Extensions.Interceptors;
> using NHibernate.Extensions.Mapping;
> using NHibernate.Mapping.ByCode;
> using NHibernate.Tool.hbm2ddl;
> using System;
> using System.Collections.Generic;
> using System.Data;
> using System.Linq;
> using System.Reflection;
>
> namespace NHibernate.Extensions
> {
> public abstract class NHibernateInitializer : IDomainMapper
>  {
>         private String MappingAssemblyName = 
>             
> System.Configuration.ConfigurationManager.AppSettings["NHibernate.Mapping.Assembly"];
>
> protected Configuration Configure;
> private ISessionFactory _sessionFactory;
>         private ModelMapper _mapper = new ModelMapper();
>         private Assembly _mappingAssembly;
>
>         public ISessionFactory SessionFactory
>         {
>             get
>             {
>                 if 
> (System.Configuration.ConfigurationManager.ConnectionStrings[System.Environment.MachineName]
>  
> == null)
>                     throw new 
> System.Configuration.ConfigurationErrorsException(String.Format("Connection 
> string {0} does not exist.", System.Environment.MachineName));
>
>                 if 
> (String.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.ConnectionStrings[System.Environment.MachineName].ConnectionString))
>                     throw new 
> System.Configuration.ConfigurationErrorsException(String.Format("Connection 
> string {0} is empty.", System.Environment.MachineName));
>
>                 return _sessionFactory ?? (_sessionFactory = 
> Configure.BuildSessionFactory());
>             }
>         }
>
>         private Assembly MappingAssembly
>         {
>             get
>             {
>                 if (String.IsNullOrEmpty(MappingAssemblyName))
>                     throw new 
> System.Configuration.ConfigurationErrorsException("NHibernate.Mapping.Assembly
>  
> key not set in application config file.");
>
>                 return _mappingAssembly ?? (_mappingAssembly = 
> Assembly.Load(MappingAssemblyName));
>             }
>         }
>
>         public void Initialize()
> {
> Configure = new Configuration();
>             Configure.SetInterceptor(new StaleInterceptor());
>             Configure.EventListeners.PreInsertEventListeners = new 
> IPreInsertEventListener[] { new EventListener() };
>             Configure.EventListeners.PreUpdateEventListeners = new 
> IPreUpdateEventListener[] { new EventListener() };
>             
> Configure.SessionFactoryName(System.Configuration.ConfigurationManager.AppSettings["SessionFactoryName"]);
> Configure.DataBaseIntegration(db =>
>                               {
>                                db.Dialect<MsSql2008Dialect>();
>                                db.Driver<SqlClientDriver>();
>                                db.KeywordsAutoImport = 
> Hbm2DDLKeyWords.AutoQuote;
>                                db.IsolationLevel = 
> IsolationLevel.ReadCommitted;
>                                db.ConnectionStringName = 
> System.Environment.MachineName;
>                                db.BatchSize = 20;
>                                db.Timeout = 10;
>                                db.HqlToSqlSubstitutions = "true 1, false 
> 0, yes 'Y', no 'N'";
>                                             db.LogFormattedSql = true;
>                               });
>             Configure.SessionFactory().GenerateStatistics();
>
> Map();
> }
>
> public void CreateSchema()
>  {
> new SchemaExport(Configure).Create(false, true);
> }
>
> public void DropSchema()
> {
> new SchemaExport(Configure).Drop(false, true);
>  }
>
>         public void UpdateSchema()
>         {
>             new SchemaUpdate(Configure).Execute(false, true);
>         }
>
> private void Map()
> {
>             _mapper.AddMappings(MappingAssembly.GetExportedTypes());
>             
> Configure.AddDeserializedMapping(_mapper.CompileMappingForAllExplicitlyAddedEntities(),
>  
> "MyWholeDomain"); 
> }
>
>         public HbmMapping HbmMapping
>         {
>             get { return _mapper.CompileMappingFor(GetDomainEntities()); }
>         }
>
>         public IList<HbmMapping> HbmMappings
>         {
>             get { return 
> _mapper.CompileMappingForEach(GetDomainEntities()).ToList(); }
>         }
>
> /// <summary>
> /// Gets the domain entities.
>  /// </summary>
> /// <returns></returns>
>         /// <remarks>by default anything that derives from EntityBase and 
> isn't abstract or generic</remarks>
>  protected virtual IEnumerable<System.Type> GetDomainEntities()
> {
>             List<System.Type> domainEntities = (from t in 
> MappingAssembly.GetExportedTypes()
>                                                 where 
> typeof(EntityBase<Guid>).IsAssignableFrom(t)
>                                                 && (!t.IsGenericType || 
> !t.IsAbstract)
>                                                 select t
>                                                ).ToList();
>
>             return domainEntities;
> }
>
>         protected virtual IEnumerable<System.Type> GetMappingClasses()
>         {
>             List<System.Type> domainEntities = (from t in 
> MappingAssembly.GetExportedTypes()
>                                                 where 
> typeof(MapBase<>).IsAssignableFrom(t)
>                                                 && (!t.IsGenericType || 
> !t.IsAbstract)
>                                                 select t
>                                    ).ToList();
>
>             return domainEntities;
>         }
> }
> }
>
>
> On Thu, Jun 26, 2014 at 8:27 PM, Michael Murphy <[email protected] 
> <javascript:>> wrote:
>
>> Ricardo,
>>
>> Thank you, very much.  That worked!  Additionally, in case any other 
>> newbie is reading this later, this page (NHibernate 3.2 mapping sample) 
>> <http://lycog.com/programming/nhibernate-32-mapping-code-basic-mapping/> has 
>> some additional info that is very helpful.  In particular if all the models 
>> and mappings are in a single assembly, rather than specifying each mapping 
>> this appears to work.  
>>
>>
>>     public InMemoryDatabaseTest(Assembly assemblyContainingMapping) {
>>       try {
>>         if (Configuration == null) {
>>           Configuration = new Configuration()
>>             .SetProperty(NHibernate.Cfg.Environment.ConnectionProvider, 
>> "NHibernate.Connection.DriverConnectionProvider")
>>             .SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, 
>> typeof(SQLite20Driver).AssemblyQualifiedName)
>>             .SetProperty(NHibernate.Cfg.Environment.ConnectionString, 
>> "Data Source=:memory:;Version=3;New=True;")
>>             .SetProperty(NHibernate.Cfg.Environment.ShowSql, "false")
>>             .SetProperty(NHibernate.Cfg.Environment.Dialect, 
>> typeof(SQLiteDialect).AssemblyQualifiedName)
>>             .SetProperty(NHibernate.Cfg.Environment.ReleaseConnections, 
>> "on_close")
>>             .SetProperty(NHibernate.Cfg.Environment.MaxFetchDepth, "1")
>>             .AddAssembly(assemblyContainingMapping);
>>
>>           //mapper = new ModelMapper();
>>           //mapper.AddMapping<ModelMap>();
>>           //mapper.AddMapping<NumberedEntityMap>();
>>           //mapper.AddMapping<PersonMap>();
>>           mapper = new ModelMapper();
>>           
>> mapper.AddMappings(assemblyContainingMapping.GetExportedTypes());
>>           mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
>>           Configuration.AddDeserializedMapping(mappings, null);
>>
>>           SessionFactory = Configuration.BuildSessionFactory();
>>         }
>>
>>         session = SessionFactory.OpenSession();
>>         connection = session.Connection;
>>         new SchemaExport(Configuration)
>>           .SetOutputFile(".\\sqlite.sql")
>>           .Execute(true, true, false, connection, Console.Out);
>>
>>       } catch (Exception ex) {
>>         throw;
>>       }
>>     }
>>
>>
>> Honestly the part that confused me was the bit about 
>> .AddAssembly(assemblyContainingMapping).  I'd expected that to take care of 
>> the mapper and mappings part.  Thank you again, Ricardo!
>>
>>
>> On Thursday, June 26, 2014 6:33:58 PM UTC-5, Ricardo Peres wrote:
>>>
>>> Try this before building the session factory:
>>>
>>> var mapper = new ModelMapper();
>>> mapper.AddMapping<ModelMap>();
>>> var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
>>> Configuration.AddDeserializedMapping(mappings, null);
>>>
>>> RP
>>>
>>>
>>> On Thursday, June 26, 2014 10:57:53 PM UTC+1, Michael Murphy wrote:
>>>>
>>>> Hello all,
>>>>
>>>> I've been using Castle ActiveRecord and am interested in starting a new 
>>>> project using just NHibernate.  I'd like to use the latest stable release 
>>>> which appears to be v3.3.3.4001.  I'd like to use the Mapping ByCode 
>>>> feature since that is similar to the Castle ActiveRecord that I have been 
>>>> working with and seems to offer me the quickest approach to working.  I've 
>>>> created a simple class 
>>>>
>>>>   public class Model {
>>>>     public virtual long ID { get; set; }
>>>>
>>>>   }
>>>>
>>>>   public class ModelMap : ClassMapping<Model> {
>>>>     public ModelMap() {
>>>>       Id(x => x.ID, m => m.Generator(Generators.Identity));
>>>>       Lazy(false);
>>>>     }
>>>>   }
>>>>
>>>>
>>>> i've created a simple MSTest Unit Test
>>>> using SyLogis.Models;
>>>> using Microsoft.VisualStudio.TestTools.UnitTesting;
>>>> namespace TestProject1
>>>> {
>>>>   [TestClass()]
>>>>   public class ModelTest {
>>>>
>>>>     static InMemoryDatabaseTest imdb = null;
>>>>
>>>>
>>>>     [ClassInitialize()]
>>>>     public static void MyClassInitialize(TestContext testContext) {
>>>>       System.Reflection.Assembly assembly = typeof(NumberedEntityMap).
>>>> Assembly;
>>>>       imdb = new InMemoryDatabaseTest(assembly);
>>>>     }
>>>>
>>>>     [TestMethod()]
>>>>     public void ID_Test() {
>>>>       Model target = new Model(); // TODO: Initialize to an appropriate 
>>>> value      
>>>>       long expected = 1; // TODO: Initialize to an appropriate value
>>>>       long actual;
>>>>       target.ID = expected;
>>>>       actual = target.ID;
>>>>       imdb.session.Save(target);
>>>>       target = null;
>>>>       target = imdb.session.Get<Model>(expected);
>>>>       Assert.AreEqual<long>(expected, target.ID);
>>>>     }
>>>>   }
>>>> }
>>>>
>>>>  and here is the inmemory piece 
>>>> using System;
>>>> using System.Collections.Generic;
>>>> using System.Linq;
>>>> using System.Text;
>>>> using NHibernate;
>>>> using NHibernate.Cfg;
>>>> using NHibernate.Tool.hbm2ddl;
>>>> using System.Reflection;
>>>> using System.Data;
>>>>
>>>>
>>>> namespace TestProject1 {
>>>>
>>>>   public class InMemoryDatabaseTest : IDisposable {
>>>>
>>>>     public static Configuration Configuration;
>>>>     public static ISessionFactory SessionFactory;
>>>>     public ISession session;
>>>>     public IDbConnection connection;
>>>>
>>>>     public InMemoryDatabaseTest(Assembly assemblyContainingMapping) {
>>>>       try {
>>>>         if (Configuration == null) {
>>>>           Configuration = new Configuration()
>>>>             .SetProperty(NHibernate.Cfg.Environment.ConnectionProvider, 
>>>> "NHibernate.Connection.DriverConnectionProvider")
>>>>             .SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, 
>>>> typeof(SQLite20Driver).AssemblyQualifiedName)
>>>>             .SetProperty(NHibernate.Cfg.Environment.ConnectionString, 
>>>> "Data Source=:memory:;Version=3;New=True;")
>>>>             .SetProperty(NHibernate.Cfg.Environment.ShowSql, "false")
>>>>             .SetProperty(NHibernate.Cfg.Environment.Dialect, 
>>>> typeof(SQLiteDialect).AssemblyQualifiedName)
>>>>             .SetProperty(NHibernate.Cfg.Environment.ReleaseConnections, 
>>>> "on_close")
>>>>             .SetProperty(NHibernate.Cfg.Environment.MaxFetchDepth, "1")
>>>>             .AddAssembly(assemblyContainingMapping);
>>>>
>>>>           SessionFactory = Configuration.BuildSessionFactory();
>>>>         }
>>>>
>>>>         session = SessionFactory.OpenSession();
>>>>         connection = session.Connection;
>>>>         new SchemaExport(Configuration)
>>>>           .SetOutputFile(".\\sqlite.sql")
>>>>           .Execute(true, true, false, connection, Console.Out);
>>>>
>>>>       } catch (Exception ex) {
>>>>         throw;
>>>>       }
>>>>     }
>>>>         
>>>>
>>>>     public void Dispose() {
>>>>       session.Dispose();
>>>>     }
>>>>   }
>>>> }
>>>>
>>>>
>>>> when i run the test it goes fine until it gets to the Save step at 
>>>> which point it throws an exception and the test details says there's no 
>>>> persister.  I'm not certain what I'm doing wrong.  I don't have any 
>>>> hbm.xml 
>>>> files to add as Embedded Resources (but I thought that was the point of 
>>>> Mapping ByCode).  I would appreciate any suggestions.  
>>>>
>>>> Also all the NHibernate Getting Started samples I can find are for 
>>>> v3.1.0 of NHibernate or even more often v2.1.x or similar.  Are there any 
>>>> Getting Started samples using v3.3.3?  If anyone has a working Visual 
>>>> Studio Solution using NHibernate v3.3.3 and could send it to me or post it 
>>>> somewhere, that would be much appreciated.  Thanks in advance.  Have a 
>>>> great day!
>>>>
>>>>
>>>>  -- 
>> You received this message because you are subscribed to the Google Groups 
>> "nhusers" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to [email protected] <javascript:>.
>> To post to this group, send email to [email protected] 
>> <javascript:>.
>> Visit this group at http://groups.google.com/group/nhusers.
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"nhusers" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/nhusers.
For more options, visit https://groups.google.com/d/optout.

Reply via email to