Search code examples
performancenhibernatehibernatecastle-activerecord

Using Lite Version of Entity in nHibernate Relations?


Is it a good idea to create a lighter version of an Entity in some cases just for performance reason pointing to same table but with fewer columns mapped. E.g If I have a Contact Table which has 50 Columns and in few of the related entities I might be interested in FirstName and LastName property is it a good idea to create a lightweight version of Contact table. E.g.

public class ContactLite
{
   public int Id {get; set;}
   public string FirstName {get; set;}
   public string LastName {get; set;}

}

Also is it possible to map multiple classes to same table?


Solution

  • It's not a good idea. Instead, always map the full class and create smaller ones that you can project on using Transformers.AliasToBean or LINQ.

    An example of the latter:

    var lightContacts = (from contact in session.Linq<Contact>()
                         where contact.Country = "Argentina"
                         select new LightContact
                                {
                                    Id = contact.Id
                                    FirstName = contact.FirstName,
                                    LastName = contact.LastName
                                })
                        .ToList();
    

    This will only select those three fields from the DB, even when filtering by a different one.

    It's worth noting that, with LINQ, you could also use an anonymous type to select any projection you want without creating additional types or mappings.