Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent Nhibernate Many to Many Mapping Way

I have two classes Order and Items

I want a method like this

class Order
{
    public virtual IList<Item> GetItems(Order order)
    {
         //get items for that order.
    }
}
class Item
{
    public virtual IList<Order> GetOrders(Item item)
    {
         //get all the orders in which that items is present.
    }
}

Is it write to create a method like this or instead should I create a property

     public virtual IList<Item> Items { get; set; }

And how should I do the mapping for this is nhibernate??

like image 894
Infant Dev Avatar asked Feb 02 '12 06:02

Infant Dev


People also ask

What is the difference between NHibernate and fluent NHibernate?

Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents, you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.

What is the use of NHibernate?

NHibernate is an ORM (Object Relational Mapper). Its purpose is to map objects in your OO application to tables in a database for persistence. Why would you need it? Because it can save you from writing a lot of tedious ADO.NET code.


1 Answers

Apparently you have a many-to-many relationship: An order can have many items and an item can belong to many orders. In a relational database you need to express this with a separate table which I presume you have - let's assume this table is called OrdersItems.

Following the Store/Product example from the Fluent NHibernate documentation you would create an Items property in an Order and an Orders property in Item:

class Order
{
    public virtual IList<Item> Items { get; protected set; }
}

class Item
{
    public virtual IList<Order> Orders { get; protected set; }
}

And the mappings:

public class OrderMap : ClassMap<Order>
{
    public OrderMap()
    {
        HasManyToMany(x => x.Items)
           .Cascade.All()
           .Table("OrdersItems");
    }
}

public class ItemMap : ClassMap<Item>
{
    public ItemMap()
    {
        HasManyToMany(x => x.Orders)
           .Cascade.All()
           .Inverse()
           .Table("OrdersItems");
    }
}
like image 166
ChrisWue Avatar answered Sep 28 '22 06:09

ChrisWue