2011-07-13 15 views
3

我有一種服務方法的情況下,分配一個POCO作爲另一個POCO的子對象不能按預期工作。我正在使用實體框架4.C#實體框架應該通過使用POCO.Id還是僅僅使用POCO來設置關係?

public void ChangeOrderCurrency(Currency currency) 
{ 
    order.CurrencyId = currency.Id; 
    order.Currency = currency; 
    // other stuff related to exchange rates etc 
} 

哪個更正確地用於設置關係? order.CurrencyId = currency.Idorder.Currency = currency

在其通過了所有的單元測試這個當前的代碼,偶爾行order.Currency = currency同時設置order.CurrencyId和order.Currency爲NULL

回答

1

更有意義使用的貨幣對象,而不僅僅是ID,因爲在檢索數據時,你很可能希望有貨幣屬性,而不僅僅是標識。當您創建/更新時,您將在兩種情況下使用Id。

0

我認爲你需要的currency附加到目標ObjectContext。如果這樣做,您將看到ordercurrency之間沒有上述代碼之間的關係。它被視爲訂單已附加到ObjectContext

//if the context is the target `ObjectContext`, then 
context.Currencies.Attach(currency); 
相關問題