Entity Framework One To Many Relation

Hi I'm new with Entity Framework, this is what i need, have two classes, let's say "Customer" and "Orders":

Class CustomerBE<br/>
{
    Public int CustomerID { get;set;}
    ...Other properties<br/>
}

Class OrderBE<br/>
{
    Public int OrderID{ get; set; }
    Public int CustomerID{ get;set;}
    Public CustomerBE Customer {get;set}
}

How to mapping the order to customer ?, i have read some others posts and some others examples, what they are doing is to create a icollection of orders in customerBE, something like:

Class CustomerBE
{
    Public int CustomerID{get;set;}
    Public Virtual ICollection Orders<orderBE>{get;set;}
}

And then they map the customer to have many orders, using the orders collection in the customer class, but, for me that is incorrect, the consumer of the class, will be able to use the orders property on the customer class to access all the orders from the customer, and i don't what to let them do that:

ICollection<OrderBE> customerOrders = customer.Orders //I don't what this

In what scenario i would like to get all the customer orders?, usually we wan't the customer orders by a given criteria (date, status, etc.), so instead of use that property, for me, i think it's better to use the orders repository to access the customer orders by a given criteria, something like: ICollection customerOrders = ordersRepository.GetCustomerOrdersByDate(customer.ID, Today.Date) //This is what i want, not orders = customer.oders so any body knows how to do the mappings between order and customer using code first approach without have an orders collection in the customer class ?

Answers


Use the Fluent API in your DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<OrderBE>().HasRequired(x => x.Customer);
}

Need Your Help

Angularjs: Cannot display array items using ng-repeat

angularjs json asp.net-mvc-3

I am using AngularJs to retrieve the data from ASP.Net Controller.

FAB transparent layer does not block the parent layer

android floating-action-button

I have a problem using Clans FloatingActionButton. I need to add a transparent layer that blocks the parent layer. The effect that I need is similar to Google Inbox.