2011-05-01 46 views
0

我有以下類別:許多使用EF 4.1代碼第一個設計

public class CartItem 
{ 
    public long Id { get; set; } 
    public int Quantity { get; set; } 
    public Product Product { get; set; } 
} 

public class Product { 
    public long Id { get; set; } 
    public string Title { get; set; } 
    public decimal Price { get; set; } 
} 

目前,我有以下配置:

modelBuilder.Entity<CartItem>().HasRequired(x => x.Product).WithMany().Map(x => x.MapKey("ProductId")); 

我想確保每當我檢索cartitem從數據庫中將會有一個產品表上的連接,所以我可以訪問產品屬性,但不能以其他方式訪問。

我基本上要能夠做到:使用配置我

string title = cartItem.Product.Title 

讓我不設置到對象異常的實例的對象引用。

回答

0

簡答題:解決你的問題,使Product屬性virtual

深入:

首先,你需要一個連接來做到這一點。 EF可以在延遲加載時正常工作(您需要virtual修改器)

其次,您可以使用Include擴展方法熱切地獲取產品。例如:

var cartItem = context.CartItems.Include(x => x.Product) 
         .Where(/*some condition*/).ToList(); 

...但你不能配置這是默認的行爲(也不是它通常是一個好主意)

第三,這是一個多到一的關係,而不是一對一(產品有很多的相關CartItems)