C# Entity Framework应该使用POCO.Id还是只使用POCO来设置关系?

3

我在一个服务方法中遇到了这样的情况:将一个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 = currency.Id还是order.Currency = currency

在这段通过所有单元测试的代码中,偶尔会出现order.Currency = currency会将order.CurrencyId和order.Currency都设置为NULL的情况。

2个回答

1

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


0

我认为你需要将currency附加到目标ObjectContext上。这样做,你就可以在不使用上面的代码的情况下看到ordercurrency之间的关系。因为订单已经附加到ObjectContext中了。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接