[英]C# Entity Framework should we set a relationship by using the POCO.Id or just the POCO?
我在服務方法中遇到一種情況,將 POCO 分配為另一個 POCO 的子 object 無法按預期工作。 我正在使用實體框架 4。
public void ChangeOrderCurrency(Currency currency)
{
order.CurrencyId = currency.Id;
order.Currency = currency;
// other stuff related to exchange rates etc
}
使用哪個更正確設置關系? order.CurrencyId = currency.Id
還是order.Currency = currency
?
在這個通過所有單元測試的當前代碼中,偶爾行order.Currency = currency
會將 order.CurrencyId 和 order.Currency 設置為 NULL
使用貨幣 object 更有意義,而不僅僅是 Id,因為當您檢索數據時,您很可能希望擁有 Currency 屬性而不僅僅是 Id。 當您創建/更新時,您將在兩種情況下都有可用的 ID。
我認為您需要將currency
附加到目標ObjectContext
。 如果這樣做,您將看到order
和currency
之間的關系,而無需上面的代碼。 它被視為訂單已經附加到ObjectContext
。
//if the context is the target `ObjectContext`, then
context.Currencies.Attach(currency);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.