|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using CommunityToolkit.Datasync.Client.Offline; |
| 6 | +using CommunityToolkit.Datasync.Server; |
| 7 | +using Microsoft.EntityFrameworkCore; |
| 8 | +using Microsoft.EntityFrameworkCore.ChangeTracking; |
| 9 | +using System.Diagnostics.CodeAnalysis; |
| 10 | +using System.Text.Json; |
| 11 | + |
| 12 | +namespace CommunityToolkit.Datasync.Client; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// The <see cref="OfflineDbContext"/> class is a base class for a <see cref="DbContext"/> that is |
| 16 | +/// used to store offline data that is later synchronized to a remote datasync service. |
| 17 | +/// </summary> |
| 18 | +public abstract class OfflineDbContext : DbContext |
| 19 | +{ |
| 20 | + /// <summary> |
| 21 | + /// Initializes a new instance of the <see cref="OfflineDbContext"/> class. The <see cref="OnConfiguring(DbContextOptionsBuilder)"/> |
| 22 | + /// method will be called to configure the database (and other options) to be used for this context. |
| 23 | + /// </summary> |
| 24 | + [ExcludeFromCodeCoverage(Justification = "Standard entry point that is part of DbContext")] |
| 25 | + protected OfflineDbContext() : base() |
| 26 | + { |
| 27 | + } |
| 28 | + |
| 29 | + /// <summary> |
| 30 | + /// Initializes a new instance of the <see cref="OfflineDbContext"/> class. The <see cref="OnConfiguring(DbContextOptionsBuilder)"/> |
| 31 | + /// method will still be called to configure the database to be used for this context. |
| 32 | + /// </summary> |
| 33 | + /// <param name="options">The options to use in configuring the <see cref="OfflineDbContext"/>.</param> |
| 34 | + protected OfflineDbContext(DbContextOptions options) : base(options) |
| 35 | + { |
| 36 | + } |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// The list of entities that are awaiting synchronization. |
| 40 | + /// </summary> |
| 41 | + public DbSet<OfflineQueueEntity> DatasyncOperationsQueue => Set<OfflineQueueEntity>(); |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// The metadata storage for each table synchronization set. |
| 45 | + /// </summary> |
| 46 | + public DbSet<DatasyncTableInformation> DatasyncTableMetadata => Set<DatasyncTableInformation>(); |
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// The <see cref="JsonSerializerOptions"/> to use for serializing and deserializing entities. |
| 50 | + /// </summary> |
| 51 | + public JsonSerializerOptions JsonSerializerOptions { get; set; } |
| 52 | + |
| 53 | + /// <summary> |
| 54 | + /// Used to manage the operations queue internally. |
| 55 | + /// </summary> |
| 56 | + internal IOperationsQueueManager OperationsQueueManager { get; set; } |
| 57 | + |
| 58 | + /// <inheritdoc /> |
| 59 | + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) |
| 60 | + { |
| 61 | + base.OnConfiguring(optionsBuilder); |
| 62 | + JsonSerializerOptions ??= new DatasyncServiceOptions().JsonSerializerOptions; |
| 63 | + OperationsQueueManager ??= new OperationsQueueManager(this); |
| 64 | + } |
| 65 | + |
| 66 | + /// <inheritdoc /> |
| 67 | + protected override void OnModelCreating(ModelBuilder modelBuilder) |
| 68 | + { |
| 69 | + modelBuilder.Entity<OfflineQueueEntity>(entity => |
| 70 | + { |
| 71 | + entity.HasKey(e => e.Id); |
| 72 | + entity.HasIndex(e => e.EntityName); |
| 73 | + entity.HasIndex(e => e.EntityId); |
| 74 | + }); |
| 75 | + |
| 76 | + modelBuilder.Entity<DatasyncTableInformation>(entity => |
| 77 | + { |
| 78 | + entity.HasKey(e => e.QueryId); |
| 79 | + entity.Property(e => e.LastSynchronization).IsRequired().HasDefaultValue(0L); |
| 80 | + }); |
| 81 | + |
| 82 | + base.OnModelCreating(modelBuilder); |
| 83 | + } |
| 84 | + |
| 85 | + /// <inheritdoc /> |
| 86 | + public virtual new int SaveChanges() => SaveChanges(true); |
| 87 | + |
| 88 | + /// <inheritdoc /> |
| 89 | + public virtual new int SaveChanges(bool acceptAllChangesOnSuccess) |
| 90 | + { |
| 91 | + StoreChangesInOperationsQueue(); |
| 92 | + return base.SaveChanges(acceptAllChangesOnSuccess); |
| 93 | + } |
| 94 | + |
| 95 | + /// <inheritdoc /> |
| 96 | + public virtual new Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) => SaveChangesAsync(true, cancellationToken); |
| 97 | + |
| 98 | + /// <inheritdoc /> |
| 99 | + public virtual new Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) |
| 100 | + { |
| 101 | + StoreChangesInOperationsQueue(); |
| 102 | + return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); |
| 103 | + } |
| 104 | + |
| 105 | + /// <summary> |
| 106 | + /// When <see cref="SaveChanges(bool)"/> or the async equivalent is called, this method looks through the changes |
| 107 | + /// to see if any should be pushed to the service. An <see cref="OfflineQueueEntity"/> is created for each change. |
| 108 | + /// </summary> |
| 109 | + /// <remarks> |
| 110 | + /// Every offline-capable entity must be derived from OfflineClientData and have a <see cref="DbSet{TEntity}"/> that |
| 111 | + /// is using the entity. |
| 112 | + /// </remarks> |
| 113 | + internal void StoreChangesInOperationsQueue() |
| 114 | + { |
| 115 | + ChangeTracker.DetectChanges(); |
| 116 | + List<EntityEntry> changedEntities = ChangeTracker.Entries().Where(t => t.State is EntityState.Added or EntityState.Deleted or EntityState.Modified).ToList(); |
| 117 | + foreach (EntityEntry entry in changedEntities) |
| 118 | + { |
| 119 | + StoreChangeInOperationsQueue(entry); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + /// <summary> |
| 124 | + /// When <see cref="SaveChanges(bool)"/> or the async equivalent is called, this method is used to add the entry via |
| 125 | + /// the operations queue manager. An <see cref="OfflineQueueEntity"/> is created for each change. |
| 126 | + /// </summary> |
| 127 | + /// <remarks> |
| 128 | + /// Every offline-capable entity must be derived from OfflineClientData and have a <see cref="DbSet{TEntity}"/> that |
| 129 | + /// is using the entity. |
| 130 | + /// </remarks> |
| 131 | + internal void StoreChangeInOperationsQueue(EntityEntry entry) |
| 132 | + { |
| 133 | + if (entry.Entity is OfflineClientEntity) |
| 134 | + { |
| 135 | + switch (entry.State) |
| 136 | + { |
| 137 | + case EntityState.Added: |
| 138 | + OperationsQueueManager.AddCreateOperation(entry); |
| 139 | + break; |
| 140 | + case EntityState.Deleted: |
| 141 | + OperationsQueueManager.AddDeleteOperation(entry); |
| 142 | + break; |
| 143 | + case EntityState.Modified: |
| 144 | + OperationsQueueManager.AddUpdateOperation(entry); |
| 145 | + break; |
| 146 | + default: |
| 147 | + throw new InvalidOperationException("Unknown entity state"); |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | +} |
0 commit comments