Join two tables in nhibernate mvc c#

2019-04-02 16:36发布

问题:

I am joining two tables using primary key and foreign key.

My tables are

  1. Item, Columns are:
    • ItemId int primary key,
    • Name varchar,
    • Price float,
    • CategoryID int foreign key,
    • QtyInStock int
  2. Category, Columns are:
    • Id int pk,
    • Category varchar,
    • Name varchar

I want to select Category on basis of ID=categoryId

I am using NHibernate 4.03 with xml configuration files.

回答1:

For unrelated entities:

var query = from item in session.Query<Item>() 
    join category in session.Query<Category>() on item.CategoryID equals category.Id;

For related entities:

Category catAlias = null;

var query = session.QueryOver<Item>()
    .JoinAlias(x => x.Category, () => catAlias);