简体   繁体   中英

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. 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM