IT:AD:Code First/Entities/Identities

Summary

When we are talking about one database, an int is always the fastest Identifier to choose as they are created in order, therefore appended to the end (compared to a Guid which has to jump all over the table looking to insert it).

In a distributed solution, where records are being created on the clients, there is no way of getting the “next id”. Guid's are often suggested.

The downside with this proposal…is the Guids. As Guids are randomly created, the inserts cause time spent re-indexing.

A classic solution is the use of a Computed Composite Distributed Id, which is a composite MachineGuid+RecordId.

That way, records are maybe not as easily idexable as ints, but far better then Guids.

In the ModelBuild, define a composite key, specifying how you will be providing values:


       modelBuilder.Entity<DistributedEntity>()
                .HasKey(m => new { m.MachineId, m.RecordId});


            modelBuilder.Entity<DistributedEntity>()
                .Property(m => m.MachineId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
            modelBuilder.Entity<DistributedEntity>()
                .Property(m => m.RecordId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Note that there are no built in mechanisms for IdentityGenerators.

The solution is to override the DbContext's save method:

Override the Repository's Save method:

    public override int SaveChanges()
    {
      var changeSet = ChangeTracker.Entries<User>();

      if (changeSet != null)
      {
        foreach (var entry in changeSet
           .Where(c => c.State == EntityState.Added || c.State == EntityState.Modified))
          {
            entry.Entity.CreatedDate = entry.Entity.AmendDate = DateTime.Now;

            if (entry.Entity.MachineId == Guid.Empty)
            {
            entry.Entity.MachineId = Guid.NewGuid();
            }
          }
      }
      return base.SaveChanges();
    }

An issuee remains when you need to find all the types of entities that can be saved, and update them.

Can be done by reflection, but a bit of a mess… Probably needs a dedicated Manager to find all various elements.

  • /home/skysigal/public_html/data/pages/it/ad/code_first/entities/identities.txt
  • Last modified: 2023/11/04 03:39
  • by 127.0.0.1