How can I generate NHibernate mapping files and DB constructs from my domain logic?

人走茶凉 提交于 2020-01-04 05:54:46

问题


I want to implement NHibernate on my domain objects in my project, but I'm not sure how I should go about generating the mapping file, and the database.

I've found some questions that kind of touch on this here and here, but I'm starting with my classes already defined, and would like to start from them and work my way down, not the other way around.

Is there any way to do this?

I'm perfectly fine with a multi-stage process, I just want to know what other people have done that was successful for them.

FYI, I want to deploy the database on SQL Server 2005.


回答1:


About the mapping: You can create the mapping with the Fluent Mapping like Gary. When you have a very uncomplicated domain model, you can use Automapping, a convention based mapping feature of FluentNhibernate:

 var sessionFactory = Fluently.Configure()  
   .Database(MsSqlConfiguration.MsSql2005  
     .ConnectionString(c => c  
       .Is(ApplicationConnectionString)))  
   .Mappings(m =>  
     m.AutoMappings.Add(AutoPersistenceModel.MapEntitiesFromAssemblyOf<Product>())  
   )  
   .BuildSessionFactory();

And that's all you need.

You can build your database with schemaexport:

var schemaExport = new SchemaExport(configuration);
schemaExport.Create(false,true);



回答2:


I like Fluent-NHibernate. See example below for mapping a User class, of course you can use XML.

The x value in the lamda expression represents the domain class.

This is very much like RoR which I like very much

public sealed class UserMap : ClassMap<User>, IMapGenerator
    {
        public UserMap()
        { 
            Id(x => x.Id)
                .WithUnsavedValue(0);
            Map(x => x.Username).TheColumnNameIs("UserName");
            Map(x => x.Password).TheColumnNameIs("Password");   
            Map(x => x.Salt).ReadOnly();

            Map(x => x.CreatedOn).ReadOnly();
            Map(x => x.CreatedBy).ReadOnly();
            Map(x => x.CreatedAt).ReadOnly();

            Map(x => x.ApprovalStatus)
                .TheColumnNameIs("ApprovalStatusId")
                .CustomTypeIs(typeof(ApprovalStatus));

            Map(x => x.DeletionStatus)
                .TheColumnNameIs("DeletionStatusId")
                .CustomTypeIs(typeof(DeletionStatus));

            References(x => x.Role).Not.Nullable();
            References(x => x.Contact);

        }

        #region IMapGenerator Members

        public System.Xml.XmlDocument Generate()
        {
            return CreateMapping(new MappingVisitor());
        }

        #endregion
    }


来源:https://stackoverflow.com/questions/812510/how-can-i-generate-nhibernate-mapping-files-and-db-constructs-from-my-domain-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!