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

发布于 2024-11-24 05:14:46 字数 482 浏览 1 评论 0原文

我在服务方法中遇到一种情况,将 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 = 货币.Idorder.Currency = 货币

在当前通过所有单元测试的代码中,order.Currency =currency 行有时会将 order.CurrencyId 和 order.Currency 设置为 NULL

I have a situation in a service method where assigning a POCO as a child object of another POCO does not work as expected. I am using Entity Framework 4.

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

Which is more correct to use to set the relationship? order.CurrencyId = currency.Id or order.Currency = currency?

In this current code which passes all unit tests, occasionally the line order.Currency = currency will set both order.CurrencyId and order.Currency to NULL

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月静好 2024-12-01 05:14:46

使用货币对象而不仅仅是 Id 更有意义,因为当您检索数据时,您很可能希望拥有货币属性而不仅仅是 Id。当您创建/更新时,您将在这两种情况下获得可用的 ID。

It makes more sense to use the currency object, not just the Id because when you retrieve data you will most likely want to have the Currency property and not just the Id. When you create / update you will have the Id available in both scenarios.

风筝在阴天搁浅。 2024-12-01 05:14:46

我认为您需要将 currency 附加到目标 ObjectContext。如果这样做,您将看到订单货币之间的关系,而无需上面的代码。它被视为订单已经附加到ObjectContext

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

I think you need to attach the currency to the target ObjectContext. If doing so, you'll see the relationship between the order and the currency without the code above. It is regarded as the order is already attached to the ObjectContext.

//if the context is the target `ObjectContext`, then
context.Currencies.Attach(currency);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文