There should not be any problems when you use long-lived dbcontext objects in your forms. You can follow the pattern described in this article
. Alternatively you could use short-living dbcontext
objects, but you have to call SaveChanges
before the context is disposed.
If you want to pass entities from one form to another you can use the CreateDetachedCopy
method from the first context and than attach the object using the AttachCopy
method to the second context and call SaveChanges
on the latter. If you use this approach and want to detach a graph of objects you have to use an appropriate FetchStrategy.
You could use a FetchStrategy
in a similar way:
DetachObjectGraph( EntitiesModel dbContext )
FetchStrategy fetchStrategy =
fetchStrategy.LoadWith<Employee>( e => e.Orders );
List<Employee> employees = dbContext.Employees.ToList();
var detachedEmployees = dbContext.CreateDetachedCopy<Employee>( employees, fetchStrategy );
To save an object and its relations you may use code similar to the following:
Category category =
Product product =
product.Category = category;
// It is enough just to pass the root object in the hierarchy.
// dbContext.Categories.Add(category); --- not needed.
The important line is number 7: product.Category = category;. It makes the relationship between the Category and the Product objects (in your case City and Station). More information about working with relations can be found in this article
I hope that this helps. If you need more assistance about handling of your context and managing relations between objects please do not hesitate to contact us again.
the Telerik team