Article information
Article relates to
Telerik OpenAccess ORM
Created by
Doroteya Agayna
Last modified
February 07, 2013
Last modified by
DESCRIPTION A typical data access scenario includes inserting new parents and children objects in the database. In this KB article, we will show you the different approaches for inserting related objects. SOLUTION Suppose you have a model like the one shown below. You need to create (insert) new Customer and Address objects, and set the relation between them. OpenAccess ORM provides a couple of ways to insert related objects: - Option 1 - Using navigation property - Option 2 - Using “raw” foreign key property - Option 3 - Using navigation collection OPTION 1 If you use the navigation property setter, your code should look like the following:
using
( EntitiesModel dbContext =
new
EntitiesModel() )
{
Customer newCustomer =
Customer();
newCustomer.Name =
"John Doe"
;
Address newAddress =
Address();
newAddress.City =
"Sofa"
newCustomer.Address = newAddress;
dbContext.Add( newCustomer );
dbContext.SaveChanges();
}
OPTION 2 If you decide to use the “raw” foreign key property setter, your code will look like the following:
dbContext.Add( newAddress );
newCustomer.AddressId = newAddress.Id;
As you see using the "raw" foreign key property in this scenario will make the things a bit complicated because you do not know the Id of the newly created address instance and have to obtain it first before assigning it to the customer. You are invoking SaveChanges twice, which means that you’re making two trips to the database. If you use the navigation property, this issue is solved easily with a simple assignment. In case, you are linking a record that already exists in the database and it is loaded in the OpenAccessContext, then you can use any of the approaches. For more information, you could refer to: How to: Insert Objects. OPTION 3 Another approach to set relations between objects is to use the collection properties. For example:
newAddress.Customers.Add( newCustomer );
In this case you need to set the IsManaged property of the collection to True. For more information, please refer to: How to: Manage Collection Properties. RECOMMENDATION Although either one of the suggested approaches is applicable regardless of the specific case, the best practice would be the usage of navigation properties whenever this is possible. WARNING If you need to use the "raw" foreign key property approach, note that it may result in additional calls to the database if one of the objects is already persisted but is not loaded in the OpenAccess context.
Resources Buy Try