18

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??

Infant Dev
  • 1,659
  • 8
  • 24
  • 48

2 Answers2

39

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");
    }
}
ChrisWue
  • 18,612
  • 4
  • 58
  • 83
  • 2
    I was missing the ".Inverse()", for future reference, if one does not use it, the table "OrdersItems" makes a double registry. – f4d0 Oct 15 '17 at 14:31
0

What would the OrdersItems look like as a class? How would this class map with table in DB if I want to use this class i order to check if there is a certain record? Would apreciate the help

Nara Omur
  • 21
  • 7
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/34665948) – David Jul 14 '23 at 10:43