views:

172

answers:

3

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?

+4  A: 

Don't map multiple classes to the same table. I tried this once and though it worked for what I was doing, I'm sure it would have bitten me later. It's better to use projections to populate the "light" classes.

dotjoe
+3  A: 

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.

Diego Mijelshon
I want to use mainly for Relations. If I have a Many-2-One relation then I don't want it to load 50 Columns.
Amitabh
Still the same case.By default, many-to-ones are loaded as proxies using the primary key, and they won't be loaded at all if you exclude them like above.
Diego Mijelshon
Unfortunately I am on nHibernate 1.2 with WCF and Lazy loading is not an option with me. So everything is eager fetched.
Amitabh
1.2 is old and totally unsupported at this point. You should really, really consider upgrading.Also, WCF shouldn't have anything to do with the decision; if it does, you are working at the wrong layer.
Diego Mijelshon
+1  A: 

I used this approach for handling an Entity without a BLOB-field (just for handling relations etc).

I had some issues regarding Implicit polymorphism, meaning I had this setup:

public class ImageWithData : Image

The inheritance made NHibernate load an ImageWithData in a second roundtrip every time I resolved an Image directly (not when related with BelongsTo or HasMany).

There is an option in NHibernate to disable this behaviour, called polymorphism="explicit" which you specify on your base-class (in my case, Image).

If it will be bad design in your case, I don't know, it all depends on why you need to lighten your entities.

jishi