Generated code - Using the entity classes, Adapter

Preface

For the Adapter template group, LLBLGen Pro will generate two VS.NET projects. This section describes code referencing both projects as it needs to interact with the database. The code used in the Adapter section of the documentation uses the General preset, which results in one class per entity. If you want two classes per entity, you've to use the TwoClasses preset, which would result in two classes per entity, one being named MyentityNameEntity, the one you'd use in your code like the code in this section.

All entity classes derive from a central, generated base class called CommonEntityBase. This class is the base class for all generated entity classes and it derives from the class EntityBase2, which is located in the ORMSupportClasses assembly. The CommonEntityBase class is usable to add code (via a partial class or using the user code regions) to all generated entities without having to generate / add that code to all entity classes separately.

Instantiating an existing entity

To load the entity's data from the persistent storage, we use the generated class related to this entity's definition, create an instance of that class and load the data (the actual entity instance) of the particular entity using a DataAccessAdapter object. As an example we're loading the entity identified with the customerID "CHOPS" into an object.
Using the primary key value
One way to instantiate the entity in an object is by passing all primary key values to the constructor of the entity class to use:

// [C#]
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
	CustomerEntity customer = new CustomerEntity("CHOPS");
	adapter.FetchEntity(customer);
}
' [VB.NET]
Using adapter As New DataAccessAdapter()
	Dim customer As New CustomerEntity("CHOPS")
	adapter.FetchEntity(customer)
End Using

This will load the entity with the primary key value of "CHOPS" into the object named customer.

FetchEntity has several overloads which offer different additional features. See the DataAccessAdapterBase class in the LLBLGen Pro runtime framework reference manual for details.
Using a related entity
Another way to instantiate this same entity is via a related entity. Adapter however doesn't support automatic data loading when you traverse a relation (lazy loading), all data has to be fetched up-front. A related entity offers a way to formulate the exact filters to fetch a specific entity very easily. Let's load the order with ID 10254, which is an order of customer "CHOPS". We can now use the loaded order to load an instance of the entity "CHOPS". The example uses the KeepConnectionOpen feature by passing true to the constructor of the DataAccessAdapter object. The example explicitly closes the connection after the DataAccessAdapter usage is finished as we've ordered it to keep it open.

// [C#]
OrderEntity order = new OrderEntity(10254);
using(DataAccessAdapter adapter = new DataAccessAdapter(true))
{
	adapter.FetchEntity(order);
	order.Customer = adapter.FetchNewEntity<CustomerEntity>(order.GetRelationInfoCustomer());
	adapter.CloseConnection();
}
' [VB.NET]
Dim order As New OrderEntity(10254)
Using adapter As New DataAccessAdapter(True)
	adapter.FetchEntity(order)
	order.Customer = adapter.FetchNewEntity(Of CustomerEntity)(order.GetRelationInfoCustomer())
	adapter.CloseConnection()
End Using

By setting order.Customer to an instance of CustomerEntity, the logic automatically sets the CustomerID field of order to the CustomerID of the specified CustomerEntity instance. Also the order object will be added to the CustomerEntity instance Orders collection. This means that the following is true after the above code snippet:

    order.CustomerID is equal to order.Customer.CustomerID
    order.Customer.Orders.Contains(order) is true

The framework keeps the two in sync as well. Consider the following situation: a new EmployeeEntity instance employee, which has an autonumber primary key field, and a new OrderEntity instance order. When the following is done: order.Employee = employee;, and the order is saved (or the employee), the field order.EmployeeID is automatically set to the new key field of the employee object after employee is saved.

If Customer is in an inheritance hierarchy, the fetch is polymorphic. This means that if the order entity, in this case order 10254, has a reference to a derived type of Customer, for example GoldCustomer, the entity returned will be of type GoldCustomer. See also Polymorphic fetches below.
Using a unique constraint's value
Entities can have other unique identifying attributes which are defined in the database and the LLBLGen Pro designer as unique constraints. In addition to the primary key these unique values can be used to load an entity. In our example, the customer entity has a unique constraint defined on its field 'CompanyName', so we can use that field to load the same entity that the CHOPS example loaded above.

Fetching the entity using a unique constraint is done via these steps: first create an empty entity class instance, set the fields which form the unique constraint to the lookup value, then fetch the entity data using a special method call of the DataAccessAdapter.

Because an entity can have more than one unique constraint, you have to specify which unique constraint to use, which means: specify a filter for the unique constraint columns. Entities with unique constraints have methods to construct these filters automatically as shown in the following example.

// [C#]
CustomerEntity customer = new CustomerEntity();
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
	customer.CompanyName = "Chop-suey Chinese";
	adapter.FetchEntityUsingUniqueConstraint(customer, customer.ConstructFilterForUCCompanyName());
}
' [VB.NET]
Dim customer As New CustomerEntity()
Using adapter As New DataAccessAdapter()
	customer.CompanyName = "Chop-suey Chinese"
	adapter.FetchEntityUsingUniqueConstraint(customer, customer.ConstructFilterForUCCompanyName())
End Using
Using a prefetch path
An easy way to instantiate an entity can be by using a Prefetch Path, to read related entities together with the entity or entities to fetch. See for more information about Prefetch Paths and how to use them: Prefetch Paths.
Using a collection class
Another way to instantiate an entity is by instantiating a collection class and fetch one or more entity definitions into that collection. This method is described in detail in the section about collection classes. You can also see Tutorials and Examples: How Do I? - Read all entities into a collection.
Using a Context object
If you want to get a reference to an entity object already in memory, you can use a Context object, if that object was added to that particular Context object. The example below retrieves a reference to the customer object with PK "CHOPS", if that entity was previously loaded into an entity object which was added to that Context object. If the entity object isn't in the Context object, a new entity object is returned. An example usage is shown below.

// C#
CustomerEntity customer = (CustomerEntity)myContext.Get(new CustomerEntityFactory(), "CHOPS");
if(customer.IsNew)
{
	// not found in context, fetch from database (assumes 'adapter' is a DataAccessAdapter instance)
	adapter.FetchEntity(customer);
}
' VB.NET
Dim customer As CustomerEntity = CType(myContext.Get(New CustomerEntityFactory(), "CHOPS"), CustomerEntity)
If customer.IsNew Then
	' not found in context, fetch from database (assumes 'adapter' is a DataAccessAdapter instance)
	adapter.FetchEntity(customer)
End If

Polymorphic fetches

Already mentioned early in this section is the phenomenon called 'Polymorphic fetches'. Imagine the following entity setup: BoardMember entity has a relation (m:1) with CompanyCar. CompanyCar is the root of a TargetPerEntityHierarchy inheritance hierarchy and has two subtypes: FamilyCar and SportsCar. Because BoardMember has the relation with CompanyCar, a field called 'CompanyCar' is created in the BoardMember entity which is mapped onto the m:1 relation BoardMember - CompanyCar.

In the database, several BoardMember instances have been stored, as well as several different CompanyCar instances, of type FamilyCar or SportsCar. Using DataAccessAdapter.FetchNewEntity, you can load the related CompanyCar instance of a given BoardMember's instance by using the following code:

// C#
CompanyCarEntity car = adapter.FetchNewEntity<CompanyCarEntity>(myBoardMember.GetRelationInfoCompanyCar());
' VB.NET
Dim car As CompanyCarEntity = adapter.FetchNewEntity(Of CompanyCarEntity)(myBoardMember.GetRelationInfoCompanyCar())

However, 'car' in the example above, can be of a different type. If for example the BoardMember instance in myBoardMember has a FamilyCar as company car set, 'car' is of type FamilyCar. Because the fetch action can result in multiple types, the fetch is called polymorphic. So, in our example, if 'car' is of type FamilyCar, the following code would also be correct:

// C#
FamilyCarEntity car = adapter.FetchNewEntity<FamilyCarEntity>(myBoardMember.GetRelationInfoCompanyCar());
' VB.NET
Dim car As FamilyCarEntity = adapter.FetchNewEntity(Of FamilyCarEntity)(myBoardMember.GetRelationInfoCompanyCar()))

Would this BoardMember instance have a SportsCar set as company car, this code would fail at runtime with a specified cast not valid exception.
DataAccessAdapter.FetchEntity and entity types in an inheritance hierarchy
DataAccessAdapter.FetchEntity() is not polymorphic. This is by design as it fetches the entity data into the passed in entity object. As it's already an instance, it would be impossible to change that instance' type to a derived type if the PK values identify an entity which is of a subtype of the type of the passed in entity instance.

In our previous example about BoardMember and CompanyCar, BoardMember is a derived type of Manager which is a derived type of Employee. If FetchEntity is called by passing in an Employee instance, and the PK identifies a BoardMember, only the Employee's fields are loaded, however if the entity is in a hierarchy of type TargetPerEntity, LLBLGen Pro will perform joins with all subtypes from the supertype, to make sure a type is stored OK.

note Note:
Be aware of the fact that polymorphic fetches of entities in a TargetPerEntity hierarchy use JOINs between the root entity's target and all subtype targets when the root type is specified for the fetch. This can have an inpact on performance.

Creating a new entity instance

To create a new entity instance, you first have to instantiate an empty entity class instance. In our example we'll use the Customer entity and we'll create a new Customer instance.

// [C#]
CustomerEntity customer = new CustomerEntity();
' [VB.NET]
Dim customer As New CustomerEntity()

To create the entity in the persistent storage, two things have to be done: 1) the entity's data (which is new) has to be stored in the new entity class instance and 2) the entity data (the entity instance) has to be persisted / saved in the persistent storage. Let's add the customer Foo Inc. to the database:

// [C#]
customer.CustomerID = "FOO";
customer.Address = "1, Bar drive";
customer.City = "Silicon Valey";
customer.CompanyName = "Foo Inc.";
customer.ContactName = "John Coder";
customer.ContactTitle = "Owner";
customer.Country = "USA";
customer.Fax = "(604)555-1233";
customer.Phone_Number = "(604)555-1234";
customer.PostalCode = "90211";
// save it. We require an adapter for this
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
	adapter.SaveEntity(customer, true);
}
' [VB.NET]
customer.CustomerID = "FOO"
customer.Address = "1, Bar drive"
customer.City = "Silicon Valey"
customer.CompanyName = "Foo Inc."
customer.ContactName = "John Coder"
customer.ContactTitle = "Owner"
customer.Country = "USA"
customer.Fax = "(604)555-1233"
customer.Phone_Number = "(604)555-1234"
customer.PostalCode = "90211"
' save it. We require an adapter for this
Using adapter As New DataAccessAdapter()
	adapter.SaveEntity(customer, True)
End Using

Customer has another field, Region, which isn't given a value. Region can be NULL and will end up as NULL in the database as it has no value in the entity saved.

The code above will save the data directly to the persistent storage (database). The SaveEntity overload used also accepts a boolean for refetch. This boolean, here the value true is specified, controls whether the data of the entity is refetched right after the save action. Adapter requires this so the entity class instance contains the latest data and is 'in-sync'. If we would have passed false or used the overload SaveEntity(customer), the entity class instance customer would have been marked 'out of sync'. This means that the entity's data has to be refetched from the database prior to reading from one of the entities properties. If you do not require the saved entity for any further processing, you don't need to refetch it and you can save yourself a roundtrip by simply omitting the 'true' in the SaveEntity() call. You can also flag an entity automatically as 'fetched' again. See below for more details about this.

The code is aware of sequences / identity columns and will automatically set the value for an identity / sequence column after the entity is physically saved inside SaveEntity(). The new value for sequenced columns is available to you after SaveEntity(), even though you haven't specified that the entity has to be refetched. This can be helpful if you want to refetch the entity later. Because the entity saved is new (customer.IsNew is true), SaveEntity() will use an INSERT query. After a successful save, the IsNew flag is set to false and the State property of the Fields object of the saved entity is set to EntityState.Fetched (if the entity is also refetched) or EntityState.OutOfSync.

note Note:
Fields which get their values from a trigger, from newid() or a default constraint calling a user defined function are not considered sequenced fields and these values will not be read back, so you'll have to supply a value for these fields prior to saving the entity. This isn't true for fields which are of type unique_identifier on SqlServer 2005 when the DQE is set in SqlServer2005/SqlServer2012 compatibility levels and the field has in the database a default value of NEWSEQUENTIALID(). See: Generated code - Database specific features

note Note:
If the entity is in a hierarchy of type TargetPerEntityHierarchy you don't have to set the discriminator value for the entity type, this is done for you automatically: just create a new instance of the entity type you want to use, and the discriminator value is automatically set and will be saved with the entity.

Modifying an existing entity instance

Modifying an entity's data (the entity instance) can be done in multiple ways:
  1. Loading an existing entity in memory, alter one or more fields (not sequenced fields) and call a DataAccessAdapter object's SaveEntity() method
  2. Create a new entity, set the primary key values (used for filtering), set the IsNew to false, set one or more other fields' values and call a DataAccessAdapter object's SaveEntity() method. This will not alter the PK fields.
  3. Via the DataAccessAdapter's UpdateEntitiesDirectly() method, specifying the primary key fields as the filter.

These different ways are described more in detail below.

Option 1: Modifying an entity instance by altering entity class instance properties.
DataAccessAdapter's SaveEntity() method will see that the entity passed to it is new or not, and will use an UPDATE query to alter the entity's data in the persistent storage and an INSERT query to insert a new instance into the persistent storage. An UPDATE query will only update the changed fields in an entity that is saved. If no fields are changed, no update is performed. If you've loaded an entity from the database into memory and you've changed one or more of its primary key fields, these fields will be updated in the database as well (except sequenced columns). Changing PK fields is not recommended and changed PK fields are not propagated to related entities fetched in memory.

An example for code using this method:

// [C#]
CustomerEntity customer = new CustomerEntity("CHOPS");
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
	adapter.FetchEntity(customer);
	customer.Phone = "(605)555-4321";
	adapter.SaveEntity(customer);
}
' [VB.NET]
Dim customer As New CustomerEntity("CHOPS")
Using adapter As New DataAccessAdapter())
	adapter.FetchEntity(customer)
	customer.Phone = "(605)555-4321"
	adapter.SaveEntity(customer)
End Using

This will first load the Customer entity "CHOPS" into memory, alter one field, Phone, and then save the entity instance back into the persistent storage. Because the loading of "CHOPS" already set the primary key, we can just alter a field and call SaveEntity() . The Update query will solely set the table field related to the entity field "Phone" to the new value.
Option 2: Update an entity directly in the persistent storage
Reading an entity into memory first can be somewhat inefficient, if all we need to do is an update of an entity row in the database. The following procedure is more efficient in that it results in just an UPDATE query, without first reading the entity data from the database. The following code performs the same update as the previous example code illustrating option 1. Because it doesn't need to read an entity first, we won't pass true to keep the connection open. Even though the PK field is changed, it is not updated, because it is not previously fetched from the database.

// [C#]
CustomerEntity customer = new CustomerEntity();
customer.CustomerID="CHOPS";
customer.Phone = "(605)555-4321";
customer.IsNew=false;
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
	adapter.SaveEntity(customer);
}
' [VB.NET]
Dim customer As New CustomerEntity()
customer.CustomerID = "CHOPS"
customer.Phone = "(605)555-4321"
customer.IsNew = False
Using adapter As New DataAccessAdapter()
	adapter.SaveEntity(customer)
End Using

We have to set the primary key field, so the Update method will only update a single entity, the "CHOPS" entity. First we specify the altering of a field, in this case Phone. Next, we have to mark the new, empty entity class instance as not being new, so SaveEntity() will use an UPDATE query, instead of an INSERT query. This is done by setting the flag IsNew to false. We'll set IsNew to false right before saving the entity. The reason to do this as the last action is to make it possible to set a field to null / Nothing using this system: setting a field to null / Nothing is a 'change of value' for new entities but for existing entities, if a field is already null / Nothing (which is the case with a new entity object) it isn't (null / Nothing changed into null / Nothing), and the field isn't seen as 'changed' and isn't updated. As the last action we call SaveEntity(). This will not load the entity back in memory. If you want that, specify 'true' with the SaveEntity() call. Doing updates this way can be very efficient and you can use very complex update constructs e.g. when you apply an Expression to the field(s) to update. See for more information about Expression objects for fields Field expressions and aggregates.

note Notes:
  • This same mechanism will work for fast deletes.
  • Setting a field to the same value it already has will not set the field to a value (and will not mark the field as 'changed') unless the entity is new.
  • Recursive saves are performed by default. This means that the DataAccessAdapter SaveEntity() logic will check whether included entities also have to be saved. If you do not want this, you can specify 'false' for recursive saves in an overload of SaveEntity() in which case only the specified entity will be saved.
  • Each entity which is saved is validated prior to the save action. This validation can be a no-op, if no validation code has been added by the developer, either through code added to the entity, or through a validator class. See Validation per field or per entity for more information about LLBLGen Pro's validation functionality.
  • (SQLServer specific) If the entity is saved into a table which is part of an indexed view, SqlServer requires that SET ARITHABORT ON is specified prior to the actual save action. You can tell the DataAccessAdapter class to set that option, by calling the SetArithAbortFlag(bool) method. After each SQL statement a SET ARITHABORT OFF statement will be executed if the ArithAbort flag is set to true. Setting this flag affects the whole application.

Option 3: Using DataAccessAdapter.UpdateEntitiesDirectly()
The DataAccessAdapter allows you to manipulate an entity or group of entities directly in the database without first fetching them into memory. Below we're setting all 'Discontinued' fields of all product entities to false if the CategoryId of the product is equal to 3. UpdateEntitiesDirectly() (as well as its method for deletes DeleteEntitiesDirectly which deletes entities directly from the persistent storage) returns the number of entities affected by the call.

// [C#]
RelationPredicateBucket bucket = 
	new RelationPredicateBucket(ProductFields.CategoryId == 3);
ProductEntity updateValuesProduct = new ProductEntity();
updateValuesProduct.Discontinued=true;
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
	int amountUpdated = adapter.UpdateEntitiesDirectly(updateValuesProduct, bucket);
}
' [VB.NET]
Dim bucket As New RelationPredicateBucket(ProductFields.CategoryId = 3)
Dim updateValuesProduct As New ProductEntity()
updateValuesProduct.Discontinued = True
Using adapter As New DataAccessAdapter()
	Dim amountUpdated As Integer = adapter.UpdateEntitiesDirectly(updateValuesProduct, bucket)
End Using
Setting the EntityState to Fetched automatically after a save
By design an entity which was successfully saved to the database gets as EntityState OutOfSync. If you've specified to refetch the entity again after the save, the entity is then refetched with an additional fetch statement. This is done to make sure that default constraints, calculated fields and elements which could have been changed after the save action inside the database (for example because a database trigger ran after the save action) are reflected in the entity after the save action. If you know that this won't happen in your application, you can get a performance gain by specifying that LLBLGen Pro should mark a successfully saved entity as Fetched instead of OutOfSync. In this situation, LLBLGen Pro won't perform a fetch action to obtain the new entity values from the database.

To use this feature, you've to set the static/Shared property EntityBase2.MarkSavedEntitiesAsFetched to true (default is false). This will be used for all entities in your application, so if you have some entities which have to be fetched after the update (for example because they have a timestamp field), you should keep the default, false. You can also set this value using the config file of your application by adding the following line to the appSettings section of your application's config file:

<add key="markSavedEntitiesAsFetched" value="true"/>

You don't need to refetch an entity if it has a sequenced primary key (Identity or sequence), as these values are read back directly with the insert statement.
FK-PK synchronization
Foreign key synchronization with a related Primary key field is done automatically in code.

For example:

This synchronization of FK-PK values is already done at the moment you set a property to a reference of an entity object, for example myOrder.Customer = myCustomer, if the entity (in this case myCustomer) is not new, or if the PK field(s) aren't sequenced fields when the entity is new. Synchronization is also performed after a save action, so identity/sequenced columns are also synchronized.

If you set a foreign key field (for example Order.CustomerID) to a new value, the referenced entity by the foreign key (relation) the field is part of will be dereferenced and the field mapped onto that relation is set to null (C#) or Nothing (VB.NET). Example:

// C#
OrderEntity myOrder = new OrderEntity();
CustomerEntity myCustomer = new CustomerEntity("CHOPS");
adapter.FetchEntity(myCustomer);
myOrder.Customer = myCustomer; 	// A
myOrder.CustomerID = "BLONP"; 	// B
CustomerEntity referencedCustomer = myOrder.Customer; // C
' VB.NET
Dim myOrder As New OrderEntity()
Dim myCustomer As New CustomerEntity("CHOPS")
adapter.FetchEntity(myCustomer)
myOrder.Customer = myCustomer 	' A
myOrder.CustomerID = "BLONP" 	' B
Dim referencedCustomer As CustomerEntity = myOrder.Customer	' C

After line 'A', myOrder.CustomerID will be set to "CHOPS", because of the synchronization between the PK of myCustomer and the FK of myOrder. At line 'B', the foreign key field CustomerID of myOrder is changed to a new value, "BLONP". Because the FK field changes, the referenced entity through that FK field, myCustomer, is dereferenced and myOrder.Customer will return null/Nothing. Because there is no current referenced customer entity, the variable referencedCustomer will be set to null / Nothing at line 'C'.

The opposite is also true: if you set the property which represents a related entity to null (Nothing), the FK field(s) forming this relation will be set to null as well, as shown in the following example:

// C#
PrefetchPath2 path = new PrefetchPath2(EntityType.OrderEntity);
path.Add(OrderEntity.PrefetchPathCustomer);
OrderEntity myOrder = new OrderEntity(10254);
adapter.FetchEntity(myOrder, path);		// A
myOrder.Customer = null; 	// B
' VB.NET
Dim path As New PrefetchPath2(EntityType.OrderEntity)
path.Add(OrderEntity.PrefetchPathCustomer)
Dim myOrder As New OrderEntity(10254)
adapter.FetchEntity(myOrder, path)		' A
myOrder.Customer = Nothing		'B

At line A, the prefetch path loads the related Customer entity together with the Order entity 10254. At line B, this myCustomer is de-referenced. This means that the FK field of myOrder creating this relation, myOrder.CustomerId, will be set to null (Nothing). So if myOrder is saved after this, NULL will be saved in the field Order.CustomerId

Deleting an entity

Deleting an entity instance from the database has the same variety of options as modifying an entity has:
  To delete an entity the simple way without fetching it first: create the new entity object, set the PK field value and call DeleteEntity. Instead of using a new entity, you can also pass an existing entity object that's already fetched into memory to DeleteEntity())

// [C#]
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
	CustomerEntity customer = new CustomerEntity("CHOPS");
	adapter.DeleteEntity(customer);
}
' [VB.NET]
Using adapter As New DataAccessAdapter(True)
	Dim customer As New CustomerEntity("CHOPS")
	adapter.DeleteEntity(customer)
End Using

It's wise to start a transaction if you want to be able to roll back the delete later on in your routine. For more information about transactions, see the section about Transactions.

note Note:
Deletes are never recursive. This means that if the delete action of an entity violates a foreign key constraint, an exception is thrown.

Entity state in distributed systems

In distributed environments, you work disconnected: the client holds data and doesn't have a connection with the server for manipulating the data in the client process, it only contacts the service for persistence and data retrieval from the database. To understand the state of an entity object the following explanation could help. Think in these steps:
  1. Create containers (entity class instances)
  2. Add data to/load data in containers (from a server for example)
  3. Show data in modifiers (forms)
  4. Data is modified and collected for persistence
  5. Collected data is send to server for persistence
  6. Process is ended
After step 6) the state should be considered void. It's up to you to ignore that and keep data around on the client. But as you work disconnected, there is no feedback from the server, so for example if you send an entity from client to server and it is saved there: you won't all of a sudden have an out-of-sync entity on the client, as that's just a copy of the object on the server. So if you want to keep on working on the client with the data, you have to consider that after step 6) you have to rewind to 1) or 2), unless you know what you can keep (read-only data for example).

If you're in 6) and you rewind to 4), you're modifying data which is out of sync with the server. LLBLGen Pro doesn't provide you with a layer which takes care of that, as you should control that yourself, because only then the developer has full control over when what happens. So when you send a UnitOfWork2 object to the server, you have to realize you're in 5) moving to 6) and it's all over for that process. If that's not the case, then you shouldn't move from 4) to 5) there, but wait and persist the data later.

Concurrency control

Adapter contains an advanced concurrency mechanism, in such a way that you can decide how to implement concurrency control in your application. It is often better to schedule concurrency aspects at a high level in your application, however if you are required to check whether a save can take place or not, you can. Similar to SelfServicing, Adapter allows you to specify a predicate expression object with the SaveEntity() method. This predicate expression is included in the UPDATE query (it's ignored in an INSERT query) so you can specify exactly if the update should take place. Adapter also allows you to implement the interface IConcurrencyPredicateFactory, and instances of that interface can be inserted into entity class instances. If such a factory is present inside an entity class instance, SaveEntity() will automatically request a predicate object from that factory to include in the UPDATE query. This way you can provide concurrency predicates during a recursive save action.

To filter on the original database values fetched into the entity to be saved, you can create for example FieldCompareValuePredicate instances which use the EntityField2's DbValue property. Even though a field is changed in memory through code, the DbValue property of a field will have the original value read from the database. You can use this for optimistic concurrency schemes. See for an example below. If the field is NULL in the database, DbValue is null (C#) or Nothing (VB.NET).

See for more information on predicates and filtering Getting started with filtering.

Below an example implementation of IConcurrencyPredicateFactory, which returns predicates which test for equality on EmployeeID for the particular order. This will make sure the Save or Delete action will only succeed if the entity in the database has still the same value for EmployeeID as the in-memory entity had when it was loaded from the database.

// [C#]
private class OrderConcurrencyFilterFactory : 
	IConcurrencyPredicateFactory
{
	public IPredicateExpression CreatePredicate(
		ConcurrencyPredicateType predicateTypeToCreate, object containingEntity)
	{
		IPredicateExpression toReturn = new PredicateExpression();
		OrderEntity order = (OrderEntity)containingEntity;

		switch(predicateTypeToCreate)
		{
			case ConcurrencyPredicateType.Delete:
				toReturn.Add(OrderFields.EmployeeID == order.Fields[(int)OrderFieldIndex.EmployeeID].DbValue);
				break;
			case ConcurrencyPredicateType.Save:
				// only for updates
				toReturn.Add(OrderFields.EmployeeID == order.Fields[(int)OrderFieldIndex.EmployeeID].DbValue);
				break;
		}
		return toReturn;
	}
}
' [VB.NET]
Private Class OrderConcurrencyFilterFactory 
	Implements IConcurrencyPredicateFactory

	Public Function CreatePredicate( _
		predicateTypeToCreate As ConcurrencyPredicateType, containingEntity As object) _
		As IPredicateExpression Implements IConcurrencyPredicateFactory.CreatePredicate

		Dim toReturn As New PredicateExpression()
		Dim order As OrderEntity = CType(containingEntity, OrderEntity)

		Select Case predicateTypeToCreate
			Case ConcurrencyPredicateType.Delete
				toReturn.Add(OrderFields.EmployeeID = _
						order.Fields(CInt(OrderFieldIndex.EmployeeID)).DbValue)
			Case ConcurrencyPredicateType.Save
				' only for updates
				toReturn.Add(OrderFields.EmployeeID = _
				 		order.Fields(CInt(OrderFieldIndex.EmployeeID)).DbValue))
		End Select
		Return toReturn
	End Function
End Class

During recursive saves, if a save action fails, which can be caused by a ConcurrencyPredicateFactory produced predicate, thus if no rows are affected by the save action, an ORMConcurrencyException is thrown by the save logic, which will terminate any transaction started by the recursive save.

To set an IConcurrencyPredicateFactory object when an entity is created or initialized, please see the section Adding your own code to the generated classes which discusses various ways to adjust the generated code to add your own initialization code which for example sets the IConcurrencyPredicateFactory instance for a particular object. You can also set an IConcurrencyPredicateFactory instance of an entity using the ConcurrencyPredicateFactoryToUse property of an entity collection to automatically set the ConcurrencyPredicateFactoryToUse property of an entity when it's added to the particular entity collection. A third way to set an entity class instance's IConcurrencyPredicateFactory is by using Dependency Injection.

Entities, NULL values and defaults

Some Entity fields are optional and aren't set to a value in all cases, which makes them undefined or null. This makes the fields nullable. Nullable fields often have a 'default' value set in the database; this is a value which is inserted by the database server when a NULL is inserted in such a column. These default values are defined in the table definition itself.

NULL values read from the database
If a field is NULL in the database, the in-memory value will be null / Nothing. This means that the CurrentValue property of the field object in the entity's Fields collection (entity.Fields[index].CurrentValue) will be null / Nothing in this situation, not a default value, and the field's property will return null / Nothing as well. 

Setting a field to NULL
To set a field to null, in a new entity, simply don't provide a value for the field. The INSERT query will not set the corresponding table field with a value, as the entity field wasn't changed (because you didn't supply a value for it). If you have set a default value for that table field, the database engine will automatically fill in the default value for that field in the database.

If you want to set a field of an existing entity to NULL, you first fetch the entity from the database and after that you set the field's property to null / Nothing. When the entity is saved after that, the UPDATE query will set the corresponding table field to NULL.

Example:

// [C#]
OrderEntity order = new OrderEntity(10254);
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
	adapter.FetchEntity(order);
	order.ShippingDate = null;
	adapter.SaveEntity(order);
}
' [VB.NET]
Dim order As New OrderEntity(10254)
Using adapter As New DataAccessAdapter()
	adapter.FetchEntity(order)
	order.ShippingDate =  Nothing
	adapter.SaveEntity(order)
End Using

You can also use one of the other methods to update an entity, e.g. to avoid the initial fetch.

To test whether a field is null, simply read the field's property and test whether it's null / Nothing.

Extending an entity by intercepting activity calls

During the entity's lifecycle and the actions in which the entity participates, various methods of the entity are called, and which might be a good candidate for your own logic to be called as well, for example when the entity is initialized you might want to do your own initialization as well. The entity classes offer a variety of methods for you to override to perform tasks in various situations. These methods all start with On and can be found in the LLBLGen Pro reference manual in the class EntityBase2. The entity classes also offer events for some situations, like the Initializing and Initialized events.

If you want to perform a given action when one of these methods are called, you can override them in the generated entity classes, preferably using the methods discussed in Adding your own code to the generated classes.

IDataErrorInfo implementation

Entity classes implement IDataErrorInfo. To utilize this interface in your own code, two methods are available: SetEntityError and SetEntityFieldError, which allows external code to set the error of a field and/or entity. If true is passed for the argument append of SetEntityFieldError, the error message is appended to an existing message for that field using a semi-colon as separator.

Entity field validation, which is triggered by setting a field to a value, sets the field's error message if an exception occurs or when the custom field validator fails. The error message is appended to an existing message.

Field data versioning

One innovative feature of LLBLGen Pro is its field data versioning. The fields of an entity, say a CustomerEntity, can be versioned and saved under a name inside the entity object itself. Later, you can decide to rollback the entity's field values at a later time. The versioned field data is contained inside the entity and can pass with the entity remoting borders and is saved inside the XML produced by WriteXml(). All fields are versioned at once, you can't version a field's values individually.

The following example loads an entity, saves its field values, alters them and then rolls them back, when an exception occurs.

// C#
CustomerEntity customer = new CustomerEntity("CHOPS");
// fetch customer here..
customer.SaveFields("BeforeUpdate");
try
{
	// show a form to the user which allows the user to
	// edit the customer entity
	ShowModifyCustomerForm(customer);
}
catch
{
	// something went wrong. Entity can be altered. Roll back
	// fields so further processing won't be affected by these
	// changes which are not completed
	customer.RollbackFields("BeforeUpdate");
	throw;
}
' VB.NET
Dim customer As New CustomerEntity("CHOPS")
' fetch customer here..
customer.SaveFields("BeforeUpdate")
Try
	' show a form to the user which allows the user to
	' edit the customer entity
	ShowModifyCustomerForm(customer)
Catch
	' something went wrong. Entity can be altered. Roll back
	' fields so further processing won't be affected by these
	' changes which are not completed
	customer.RollbackFields("BeforeUpdate")
	Throw
End Try

LLBLGen Pro Runtime Framework v4.1 documentation. ©2013 Solutions Design bv