Archive for the ‘NHibernate’ category

Server-side paging, sorting, filtering and grouping with the Kendo UI Grid and NHibernate

December 17, 2015

KendoNHIntegration3

Trying to integrate Telerik’s Kendo Grid with NHibernate and you keep getting a nasty exception? How to get server-side data operations working without experiencing the grouping error?

Find out more.

https://dionscher.wordpress.com/technical-articles/server-side-paging-sorting-filtering-and-grouping-with-the-kendo-ui-grid-and-nhibernate/

 

 

Advertisements

NHibernate – beginning of the end?

August 2, 2013

Being a huge fan of NHibernate, I really hope the concerns of this article don’t come to pass.  But I too have noticed what I consider to be a fragmentation in NHibernate’s growth path. Libraries like the amazing and popular Fluent NHibernate in competition with Loquacious Configuration. A multitude of query methods – perhaps too many…? A less than complete Linq to NHibernate implementation. This article talks around doubts surrounding the future of NHibernate, largely due to it’s lack of contributor support.

The State of Entity Framework and NHibernate

http://weblogs.asp.net/ricardoperes/archive/2013/05/29/the-state-of-entity-framework-and-nhibernate.aspx

Having used Entity Framework 5 for the last while, I am almost impressed. I still loathe the designer and code-first is improving with every release. I think the biggest thing for me is how clean the Linq implementation is. Now, if only they could improve that performance….

Disabling caching in Fluent NHibernate for a specific override

December 18, 2012

We’re using convention based mapping with Fluent NHibernate. The mapping looks like so:

.Conventions.Add
(
  Table.Is(x => string.Concat(x.EntityType.Name.ToLower(), "s")),
  PrimaryKey.Name.Is(x => "Id"),
  DefaultLazy.Always(),
  DefaultCascade.SaveUpdate(),
  AutoImport.Never(),
  Cache.Is(x => x.ReadWrite())
)

For most of our objects this is perfect but on certain objects I wish to disable the 2nd level cache. However it doesn’t appear that I can do this. There is no fluent option for Cache.None. I’ve even tried Not.Cache() but that didn’t work either.

How can one disable the cache for certain selected model objects?

Ok, I managed to find it after some digging around jogged an idea:

  1. Remove the shortcut “Cache.Is(x => x.ReadWrite())”
  2. Create a new convention class:

public class CacheableConvention: IClassConventionAcceptance, IClassConvention 
{
    public void Accept(IAcceptanceCriteria criteria)
    {
        criteria.Expect(x => x.EntityType.IsNotAny(typeof(Content), typeof(InstanceSetting))); 
    }

    public void Apply(IClassInstance instance)
    {
        instance.Cache.ReadWrite();
    }
}
  1. Add the convention to the AutoMappings.
  2. Done!

How to check your Fluent mapping against HBM mapping when using Fluent NHibernate?

June 1, 2012

Recently I was tasked with converting an existing application’s NHibernate mappings to Fluent NHibernate. The original mappings were done as XML-based hbm files. Bottom line is that there was nothing wrong with the hbm mappings, and one is able to mix-and-match hbm mappings with fluent mappings, but for the purposes of the project we decided is preferable to settle on one standard.

One particular mapping proved to be a bit challenging to convert. The hbm XML file contained the following map:


<bag name="Features" access="field.camelcase-underscore" cascade="all" lazy="true" table="WebsiteFeatures">
 <cache usage="read-write"/>
 <key column="WebsiteID"/>
 <element column="Feature" type="Model.Types.FeatureType, Model" not-null="true"/>
</bag>

After creating the fluent map, I wanted to check that I was a close to the original hbm mapping as possible. To do this is actually quite simple. Just configure your Fluent configuration to export its mappings to file, like so:


return Fluently.Configure()
  .Database(MsSqlConfiguration.MsSql2008
  .ConnectionString(x => x.FromConnectionStringWithKey("DefaultConnection"))
  .Mappings(x => x.FluentMappings.AddFromAssemblyOf ().ExportTo(@"C:\BloggingTemp\"))
  .BuildConfiguration();

The XML mappings are then exported to your selected directory and you’re able to compare them against your original hbm maps.

How to map a NHibernate <MAP> tag in FluentNhibernate?

April 21, 2012

Introduction

One of the common problems experienced when using Fluent NHibernate is how to convert a particular mapping, previously in HBM file format, to a Fluent NHibernate syntax.

In this tutorial example I will model an Entity to Entity-Settings structure. Typically used to stored additional information on the entity when you don’t want to designate a particular column to do the job. So we provide an open structure in the form of a key-value pair table.

In classic NHibernate HBM files you would use a <MAP> element to represent this relationship. However in Fluent NHibernate it’s mapped slightly differently.

Dependencies:

  • NHibernate 3.2.400
  • FluentNHibernate 1.3.0.717

Tutorial:

This is the database structure we will deal with:

I’m intentionally keeping it simple. We have a Customer table that holds basic customer information and a CustomerSettings table which hold key-value pair string information – in other words it holds whatever we want that fits the structure of a key-value pair. I also want any changes to the Customer settings to be saved when I persist the Customer object.

My classes look as follows:

    public class Customer
    {
        public Customer()
        {
            Settings = new Dictionary();
        }

        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Surname { get; set; }
        public virtual IDictionary Settings { get; set; }
    }

The mapping is actually really simple but it took forever to figure out how to do it properly. So the classmap looks like so:

    public class CustomerMap : ClassMap
    {
        public CustomerMap()
        {
            Table("Customer");
            Id(x => x.Id).Not.Nullable().GeneratedBy.Identity();
            Map(x => x.Name).Not.Nullable().Length(50);
            Map(x => x.Surname).Not.Nullable().Length(50);

            HasMany(x => x.Settings)
            .Table("CustomerSettings")
            .KeyColumn("CustomerId")
            .AsMap(
                index => index.Column("`Key`").Type(),
                element => element.Column("Value").Type()
            )
            .Cascade.All();
        }
    }

And that’s it! Now all you need to do is a basic NHibernate save, with your customer information and settings and the settings will also save in your cascade:

            DatabaseContext.Initialize();

            var customer = new Customer
                        {
                            Name    = "Joe",
                            Surname = "Blogs"
                        };
            customer.Settings.Add("Age", "30");
            customer.Settings.Add("Country", "ZA");

            using (var session = DatabaseContext.SessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    session.SaveOrUpdate(customer);
                    tx.Commit();
                }
            }