XAF - How to generate a sequential number for a persistent object within a database transaction with Entity Framework Core
This example illustrates how to implement a business object with an identifier field with autogenerated sequential values.
This Readme focuses on Entity Framework Core. For information on how to achieve the same functionality with XPO, see the Readme.md file in the XPO solution's folder.
Entity Framework Core allows you to set up generation of sequential values for non-key data fields as described in the following article in the Entity Framework Core documentation: Generated Values - Explicitly configuring value generation.
Use the steps below to generate sequential values for a business object's property so that the property is assigned a value once the object has been saved to the database:
-
Add the
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
attribute to the required business object property:public class Address : BaseObject { // ... [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public virtual long SequentialNumber { get; set; } // ... }
-
Add the following code to the DbContext's
OnModelCreating
method implementation so that the generated values are always displayed in the UI immediately after the object has been saved:public class GenerateUserFriendlyIdEFCoreDbContext : DbContext { // ... protected override void OnModelCreating(ModelBuilder modelBuilder) { // ... modelBuilder.Entity<Address>().UsePropertyAccessMode(PropertyAccessMode.FieldDuringConstruction); } }
As an alternative technique, you can use a database-specific sequence object to generate sequential values as described in the following article: Sequences.
(you will be redirected to DevExpress.com to submit your response)