2012-07-16 229 views
0

嗨,我是新的實體框架,這正是我需要的,有兩個班,讓我們說「客戶」和「訂單」:實體框架一對多關係

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

如何映射順序?客戶,我看過一些其他的職位和一些其他的例子,他們在做什麼是customerBE創建訂單的ICollection的,是這樣的:

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

然後它們映射客戶有很多訂單,使用客戶類中的訂單集合,但是,對我來說這是不正確的,該類的消費者將能夠使用客戶類的訂單屬性來訪問來自客戶的所有訂單,並且我不會讓他們這樣做:

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



在什麼情況下我想獲得所有客戶的訂單?通常我們通過一個給定的標準(日期,狀態等)wan't的客戶訂單,所以不是使用該財產,對於我來說,我認爲最好使用訂單資料庫來按給定的標準訪問客戶訂單,例如:


ICollection customerOrders = ordersRepository.GetCustomerOrdersByDate(customer.ID, Today.Date) //This is what i want, not orders = customer.oders


因此,任何機構都知道該怎麼做的訂單和客戶之間的映射使用代碼第一種方法不具有在客戶類的訂單收藏?

回答

1

使用流利的API在你的DbContext類:

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

謝謝你會嘗試,這將加載正確的客戶信息,訂單? – Rafael 2012-07-16 17:45:11