C#Entity Framework我们应该使用POCO.Id还是仅使用POCO设置关系?

我有一种服务方法的情况,其中将POCO指定为另一个POCO的子对象不能按预期工作。 我正在使用Entity Framework 4。

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

在当前通过所有unit testing的代码中,有时行order.Currency = currency将orderCurrencyId和order.Currency设置为NULL

使用货币对象更有意义,而不仅仅是Id,因为当您检索数据时,您很可能希望拥有Currency属性而不仅仅是Id。 创建/更新时,您将在两种方案中都可以使用Id。

我认为您需要将currency附加到目标ObjectContext 。 如果这样做,您将在没有上述代码的情况下看到ordercurrency之间的关系。 它被认为是已经附加到ObjectContext的顺序。

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