Tuesday, February 17, 2015

Entity Framework and Many to Many Relationship - Simple Example

If you want to do Many to Many relationship in Entity Framework the work is quite simple:

  1. Create two classes say Order and Product
  2. Establish a navigational property between the two classes 
  3. You're done. 
So lets take a look at this, the following, as in the example above is Order class

Public Class Order
{
    public int ID {get; set;}
    public string Description {get; set;}
    public virtual ICollection<Product> Products {get; set;}

    public Order()
    {
         this.Products = new List<Product>();
    }

}

The class is a basic class with an ID that is an integer, another property called Description which is of type string, and finally there is a collection of Products. The collection of products is what starts the relationship to Product entity or class. The collection is then instantiated in the constructor as a List. 

The following is the Product class

Public Class Product
{
    public int ID {get; set;}
    public string Name {get; set;}
    public virtual ICollection<Order> Orders {get; set;}



 public Order()
 {
     this.Orders = new List<Order>();
  }

}


The product class is also quite simple in this example, it contains an ID of type integer, a Name of type string, and another collection - this time it is a collection of Orders. This then completes, for this example the many to many relationship. 

Therefore in reading the two entities you would say an Order has collection of Products (or many products) and Products has a collection of Orders (or many orders).

What is Virtual

You may have noticed that there is a virtual keyword before ICollection. The virtual keyword is to establish Lazy Loading. This means that when you retrieve the entity the collection is not loaded immediately, instead it is loaded when you start using it. 

Lets Continue

So to use the many to many relationship in the code you simply need to use the List functions to add/remove. For example to add a product to an instance of a order you would do something like this:


Order _order = New Order(){Description = "My Description"};
Product _product = new Product(){Name = "My Product"};
_order.Products.Add(_product);

In the above code, what we are doing is creating a new instance of Order and note that I'm assigning the value to the Description at the same time as creating the new object. I then create an instance of a Product, otherwise retrieve a product. I then add the product to the collection of Products in the Order object.

If you were using this in a database context you would need to add the Order to the Database, and then save the changes.  




0 comments:

Post a Comment