GUID Generation

    GUID has advantages and disadvantages. You can find many articles on the web related to this topic, so we will not discuss all again, but will list the most fundamental advantages:

    • It allows to determine the primary key on the client side, without needing a database round trip to generate the Id value. This can be more performant while inserting new records to the database and allows us to know the PK before interacting to the database.
    • GUIDs are naturally unique which has some advantages in the following situations if;
      • You need to integrate to external systems.
      • You need to split or merge different tables.
    • GUIDs are impossible to guess, so they can be more secure compared to auto-increment Id values in some cases.

    While there are some disadvantages (just search it on the web), we found these advantages much more important while designing the ABP Framework.

    The most important problem with GUID is that it is not sequential by default. When you use the GUID as the primary key and set it as the clustered index (which is default) for your table, it brings a significant performance problem on insert (because inserting new record may need to re-order the existing records).

    One good solution to this problem is to generate sequential GUIDs, which is provided by the ABP Framework out of the box. IGuidGenerator service creates sequential GUIDs (implemented by the SequentialGuidGenerator by default). Use IGuidGenerator.Create() when you need to manually set Id of an entity.

    Example: An entity with GUID primary key and creating the entity

    Assume that you’ve a Product that has a key:

    This service injects the IGuidGenerator in the constructor. If your class is an application service or deriving from one of the other base classes, you can directly use the GuidGenerator base property which is a pre-injected IGuidGenerator instance.

    AbpSequentialGuidGeneratorOptions is the that is used to configure the sequential GUID generation. It has a single property:

    • DefaultSequentialGuidType ( of type SequentialGuidType): The strategy used while generating GUID values.

    Database providers behaves differently while processing GUIDs, so you should set it based on your database provider. SequentialGuidType has the following enum members:

    • SequentialAtEnd (default) works well with the SQL Server.
    • SequentialAsString is used by and PostgreSQL.