[英]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.