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

不羁的心 提交于 2019-12-07 13:33:41

问题


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


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/6686875/c-sharp-entity-framework-should-we-set-a-relationship-by-using-the-poco-id-or-ju

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!