Article relates to
Telerik OpenAccess ORM
February 07, 2013
Last modified by
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
If you use the navigation property setter, your code should look like the following:
( EntitiesModel dbContext =
Customer newCustomer =
Address newAddress =
newCustomer.Address = newAddress;
dbContext.Add( newCustomer );
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.
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.
Copyright © 2016, Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
Progress, Telerik, and certain product names used herein are trademarks or registered trademarks of Progress Software Corporation and/or one of its subsidiaries or affiliates in the U.S. and/or other countries. See Trademarks or appropriate markings.