C# 实体框架我们应该使用 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 = 货币.Id
或order.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用货币对象而不仅仅是 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.
我认为您需要将
currency
附加到目标ObjectContext
。如果这样做,您将看到订单
和货币
之间的关系,而无需上面的代码。它被视为订单已经附加到ObjectContext
。I think you need to attach the
currency
to the targetObjectContext
. If doing so, you'll see the relationship between theorder
and thecurrency
without the code above. It is regarded as the order is already attached to theObjectContext
.