NHibernate IList to List

房东的猫 提交于 2019-11-30 15:45:17

That's not how NHibernate works. You don't get to tell it what the concrete types of your domain model objects are. You only get to tell it what the base types and interfaces are. Then it gets to choose how to implement the domain types efficiently.

For example, NHibernate uses its own internal implementation of IList<T> that knows how to do lazy loading.

Moreover, NHibernate uses its own internal implementation of Building from your domain model. It is not necessarily the case that all the Building objects you will be using with NHibernate will have, as their concrete type, Building. It is only true that they will be Buildings, whether Building is the concrete type of your object, or whether it is the base type of the concrete type of your object.

But this is the right thing to do, since you are supposed to be using interfaces and base types instead of concrete types anyway. NHibernate helps you use all the right approaches to programming.

Now, why do you need a List<Building> per se? Why will IList<Building> not suffice?

Why do you need a concrete List object, when you can do everything you want with an IList?

If it absolutely has to be a concrete list, you have two options.

First, simply cast the IList<Building> to List<Building>. This will only work if the underlying type is a List<Building>, which I personally doubt.

Second, call the ToList() extension method on it:

Buildings = (List<Building>)session.CreateCriteria(typeof(Building)).AddOrder(Order.Asc("buildingName")).List<Building>().ToList();

I personally recommend that you do neither and use the IList instead.

How about using the constructor of List<T> that takes an IEnumerable<T>? Then you can use:

Buildings = new List<Building>(session.CreateCriteria(typeof(Building)).AddOrder(Order.Asc("buildingName")).List<Building>());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!