回答

10

一對一

public class One 
{ 
    public int Id {get;set;} 
    public virtual Two RelationTwo {get;set;} 
} 

public class Two 
{ 
public int Id {get;set;} 
public virtual One RelationOne {get;set;} 
} 

需要注意的事項,它必須是虛擬

一對多

public class One 
{ 
    public int Id {get;set;} 
    public virtual ICollection<Two> RelationTwo {get;set;} 
} 

public class Two 
{ 
public int Id {get;set;} 
public virtual One RelationOne {get;set;} 
} 

多對多

public class One 
{ 
    public int Id {get;set;} 
    public virtual ICollection<Two> RelationTwo {get;set;} 
} 

public class Two 
{ 
public int Id {get;set;} 
public virtual ICollection<One> RelationOne {get;set;} 
} 

注意,它需要的ICollection

以下鏈接也許有用,clickclick

希望這有助於。

編輯

更新包括一個不少。

編輯#2

更新,以包括做發票<一個潛在的 - 這是由評論請求>產品方案。

注:這是未經測試,但應該把你在正確的方向

public class Invoice 
{ 
    public int Id {get;set;} 
    //.. etc. other details on invoice, linking to shipping address etc. 

    public virtual ICollection<InvoiceProduct> Items {get;set;} 
} 

public class InvoiceProduct 
{ 
    public int Id {get;set;} 
    public int Quantity {get;set;} 
    public decimal Price {get;set;} // possibly calculated 
    //.. other details such as discounts maybe 

    public virtual Product Product {get;set;} 
    public virtual Invoice Order {get;set;} // maybe but not required 
} 

public class Product 
{ 
    public int Id {get;set;} 
    //.. other details about product 
} 

使用這個然後你可以通過發票上的所有元素的和隨後的foreach能夠顯示發票明細關於每件商品以及產品本身的描述。

+2

我不相信他們需要虛擬(但我強烈建議讓他們虛擬)。如果它們未被標記爲虛擬,則該關係將仍然存在,但是EF不會使用延遲加載,並且只會在對應實體已加載到會話中時才加載關係的另一側。此外,對於一對多,如何做到這一點可以通過您的答案來推斷,並不需要雙方的參考,儘管它可能對應用程序的需求有所幫助。 – 2011-01-19 14:06:54

相關問題