Using Lite Version of Entity in nHibernate Relations?

 ̄綄美尐妖づ 提交于 2020-02-03 05:29:05

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2435111/using-lite-version-of-entity-in-nhibernate-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!