Thursday, May 5, 2011

Joins in fluent nhibernate

Hi, I am using fluent nhibernate.

example:

i have 3 tables i.e.

CUSTOMER CustomerId pk CustomerName

PRODUCT ProductId pk ProductName

Cust_Product cust_prodId pk ProductId fk CustomerId fk

Now, I want to show customername, productnae

so, how do i write mapping class for the same.

i want to use

session.CreateCriteria(typeof("className")).List() like this. how do i do this..?

From stackoverflow
  • If you're looking for a full tutorial on how to do this, I recommend the FNH wiki or one of the many blog postings which can be found through Google.

    However, you're trying to implement a many-to-many relationship here, and that seems to throw a lot of people off. Here's a rough guide:

    On your Customer class, you'll need a collection like:

    IList<Product> Products { get; private set; }
    

    And similarly, on your Product class:

    IList<Customers> Customers { get; private set; }
    

    You start off a many-to-many map with the HasManyToMany function:

    public class CustomerMap : ClassMap<Customer>
    {
        public CustomerMap()
        {
            // other mappings
    
            HasManyToMany<Product>(x => x.Products)
                .WithTableName("Cust_Product")  // Specifies the join table name
                .WithParentKeyColumn("CustomerId") // Specifies the key joining back to this table (defaults to [class]_id, Customer_id in this case)
                .WithChildKeyColumn("ProductId")
                .FetchType.Join(); // Instructs NHibernate to use a join instead of sequential select
        }
    }
    

    Then repeat the process for the other side of the relationship (the Customers property on the Product class).

    Rahul Somwanshi : thanks a lot Stuart ...

0 comments:

Post a Comment