My model is implemented in an own DLL, where also the generated App.config is placed. The application itself “had” no App.config. No context was initialized (direct access in DLL only). And i get an error, which was solved by copy the connection string into the application new by hand generated App.config.
This case was a little bit redundant for me and I decided to get the EntityConnection by writing it myself. Now the problematic code, which works with the redundant version and not in the own implementation.
public Discount GetDiscountByOffer(int discountId)
{
// Own implementation, redundant one without passed connection parameter
using (context2 = new SalesEntities(Configuration.EntityConnection))
{
return context2.Discounts.Single(d => d.ID == discountId);
}
}
In another class I call this method and assign it to a customer. Also here i make a new context. Code simplified:
// Own implementation, redundant one without passed connection parameter
using (context1 = new SalesEntities(Configuration.EntityConnection))
{
var customer = GetCustomer(10004);
customer.ActualDiscount = GetDiscountByOffer(5); // here is the call and
// the error
}
The error ahows that ObjectContext (context1) was closed, what I don’t understand. What has context2 to do with context1? I bet that both share the same reference, but it’s not logical for me. The EntityConnection is also initialized new each time I pass the parameter.
In the redundant version this code works.
Get the object from context2, attach it to context1, then set the customer’s property.
MSDN explanation:
http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attach.aspx
Read ‘The problems of working with multiple ObjectContext instances’ below:
http://dotnetslackers.com/articles/ado_net/Managing-Entity-Framework-ObjectContext-lifespan-and-scope-in-n-layered-ASP-NET-applications.aspx#the-problems-of-working-with-multiple-objectcontext-instances