简体   繁体   English

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

[英]C# Entity Framework should we set a relationship by using the POCO.Id or just the POCO?

I have a situation in a service method where assigning a POCO as a child object of another POCO does not work as expected.我在服务方法中遇到一种情况,将 POCO 分配为另一个 POCO 的子 object 无法按预期工作。 I am using Entity Framework 4.我正在使用实体框架 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 ? order.CurrencyId = currency.Id还是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在这个通过所有单元测试的当前代码中,偶尔行order.Currency = currency会将 order.CurrencyId 和 order.Currency 设置为 NULL

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.使用货币 object 更有意义,而不仅仅是 Id,因为当您检索数据时,您很可能希望拥有 Currency 属性而不仅仅是 Id。 When you create / update you will have the Id available in both scenarios.当您创建/更新时,您将在两种情况下都有可用的 ID。

I think you need to attach the currency to the target ObjectContext .我认为您需要将currency附加到目标ObjectContext If doing so, you'll see the relationship between the order and the currency without the code above.如果这样做,您将看到ordercurrency之间的关系,而无需上面的代码。 It is regarded as the order is already attached to the ObjectContext .它被视为订单已经附加到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