繁体   English   中英

C# 实体框架我们应该使用 POCO.Id 还是仅使用 POCO 来设置关系?

[英]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 如果这样做,您将看到ordercurrency之间的关系,而无需上面的代码。 它被视为订单已经附加到ObjectContext

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM