-
Notifications
You must be signed in to change notification settings - Fork 4
Key Generation
Nemo provides two key generation mechanisms. Both of them are applied declaratively using attributes:
Generate.NativeAttributeGenerate.UsingAttribute
Generate.NativeAttribute defers key generation to an underlying storage. All CUD operations in Nemo are convention based stored procedures. Hence, properties with such an attribute produce output parameters when ObjectFactory.Insert is called. Nemo applies values of output parameters to pertinent properties as soon as an operation completes. Calling GenerateKey() extension method will not fill in the values of properties decorated with Generate.NativeAttribute.
public class Order
{
[PrimaryKey, Generate.Native]
public int OrderId { get; set; }
...
}Generate.UsingAttribute uses an implementation of IIdGenerator interface. Nemo is shipped with default implementations of the interface:
GuidGeneratorCombGuidGeneratorUniqueNegativeNumberGeneratorHiLoGenerator
Note: HiLoGenerator option requires a valid connection string and a presence of a special table (can be defined via Nemo configuration) that will be created if not present
public class Order
{
[PrimaryKey, Generate.Using(typeof(UniqueNegativeNumberGenerator))]
public int OrderId { get; set; }
...
}Any time Insert() (or Save()) extension method is invoked, Nemo calls GenerateKey() automatically ( provided that no key has been generated so far).
// Assuming UniqueNegativeNumberGenerator is used
var order = new Order();
// Set all property values except for OrderId
Debug.Assert(order.OrderId == 0); // OrderId has not been set yet
order.Insert();
Debug.Assert(order.OrderId < 0); // OrderId should be set during the insertOnce GenerateKey() extension method is invoked manually, it will not be invoked during the insert anymore.
// Assuming UniqueNegativeNumberGenerator is used
var order = new Order();
// Set all property values except for OrderId
Debug.Assert(order.OrderId == 0); // OrderId has not been set yet
order.GenerateKey();
Debug.Assert(order.OrderId < 0); // OrderId should be set after call to GenerateKey
var id = order.OrderId;
order.Insert();
Debug.Asser(id == order.OrderId); // OrderId should not be modified by the insert