Make a SQL Query to Nhibernate

跟風遠走 提交于 2019-12-20 07:51:08

问题


How do I get this SQL query to Nhibernate?

SELECT Customer.name
FROM Company INNER JOIN Customer ON Company.CompanyId = Customer.CompanyId
where CompanyId = 2

回答1:


If you are familiar with LINQ it is very very simple,
you have to directly access the reference filed just as an entity. and you will get the properties of that entity and so on you can access till the nth node.

Nhibernate will take care of reference fields as entities..

        //Here is the sample this may work 
        //CustomerList is a nhibernate entity list.
        //CompanyId is also an entity which is a reference to the CompanyId of Company table.
        // you will get the list of customers based on condition. 
        var CustomerList = new List<Customer>();
        var custList = from cust in CustomerList where cust.CompanyId.CompanyId == 2 select cust;



回答2:


Assuming you've got a company which represents the company with ID 2. You can use an ICriterion:

return this.GetSession().CreateCriteria<Customer>()
    .Add(Restrictions.Eq("Company", company))
    .List<Customer>();

This will return a list of the Customers associated with the company (assuming the property on the Customer class is called "Company").

To get the names just do:

customers.Select(c => c.name);

I'd suggest this approach as you know all the customers will be loaded in one db hit rather than lazily loading them one at a time.



来源:https://stackoverflow.com/questions/24114655/make-a-sql-query-to-nhibernate

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