开发者

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 Contac开发者_如何学GotLite
{
   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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜