What is the difference between NHibernate.Mapping.

2020-07-10 20:05发布

问题:

I'm learning about NHibernate, where the class mapping, I learned, is done with XML. I understand that Fluent NHibernate came about as a strongly-typed replacement for the XML-style of mapping. Indeed, here is the fluent-nhibernate tag description:

Fluent NHibernate lets you write NHibernate mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.

Then later I was using NHibernate Mapping Generator to create mappings and domain classes from my existing database, and it generated mapping code like this:

using NHibernate.Mapping.ByCode.Conformist;
using NHibernate.Mapping.ByCode;

namespace MyNamespace.Infrastructure.Mappings
{
    public class MyItemMapping  : ClassMapping<MyItem> 
    {
        public MyItemMapping()
        {
            Table("MyItems");
            Schema("master");
            Lazy(true);
            Id(x => x.ID, map => map.Generator(Generators.Assigned));
            Property(x => x.Status, map => map.NotNullable(true));
            Property(x => x.DueDate, map => map.NotNullable(true));
            Property(x => x.NextReminderDate);
            Property(x => x.DatePaid);
            Property(x => x.Notes);
        }
    }
}

Lo and behold, it's using a NHibernate.Mapping.ByCode.Conformist.ClassMapping<T> class. What gives? If NHibernate in fact does have it's own strongly-typed, non-XML mapping capabilities, then why do I need Fluent NHibernate?

I've noticed some differences between NHibernate.Mapping.ByCode.Conformist.ClassMapping<T> and FluentNHibernate.Mapping.ClassMap<T>. For example, the former doesn't support References, e.g. References(x => x.BillingItemID);, to relate entities via the foreign key. Maybe there's another way of doing that.

回答1:

FluentNHibernate was around before NHibernate had MappingByCode, now that it does, FluentNHibernate is obsolete, it's also less efficient than Nhibernate's own MappingByCode because it generates normal XML mapping files at startup and uses them internally.

The only downside to NHibernate MappingByCode is that there isn't much documentation for it, the best I've found is here:

http://notherdev.blogspot.co.uk/2012/02/nhibernates-mapping-by-code-summary.html

But I would use NHibernate's version regardless. I'm under the impression that NHibernate's version actually supports more than FluentNhibernate does as well, the equivalent of that Reference would just be the opposite side a relationship, e.g. if the parent is mapped as OneToMany() then the equivalent child side map to Fluent's Reference would be a ManyToOne(). I think that's the case anyway.