Thursday, March 19, 2009

Entity Framework – Set reference from method

Usually entity types are returned from processing methods in a layered architecture. E.g. I have a Product and I want to set the currency of the price which is stored in a different table. It means I have a foreign key to the price.

I tried to set the reference in Entity Framework something like this:

  1: Product product = new Product(); 
  2: product.Name = "aaa"; 
  3: product.Price = 12; 
  4: product.Currency = CurrencyManager.GetCurrency("USD"); 
  5: context.AddToProduct(product); 
  6: context.SaveChanges();

Unfortunately this won’t work. If GetCurrency() returns a currency returned by a LINQ query, it will be referenced by a context different from my current context. An object can’t be attached to two contexts at the same time.

The solution is simple. In the GetCurrency() method you will need detach the object returned by the query:

  1: var currencies = context.CurrencyCode.Where(c => c.Code == code);
  2: if (currencies.Count() > 0)
  3: {   
  4:     var currency = currencies.First();
  5:     context.Detach(currency);
  6:     return currency;
  7: }
  8: else
  9: {
 10:     return null;
 11: }

And when you call the GetCurrency() method, simply attach the object to the current context and set the reference to that:

  1: var currecy = CurrencyManager.GetCurrency("USD");
  2: context.Attach(currency);
  3: product.Currency = currency;