Hello everyone Please help me I want to achieve this task for existing users, but it is not working.This is my code ```
public partial class AddCodePropertiesToUserTable : Migration { private readonly DbContext _dbContext; /// <inheritdoc /> public AddCodePropertiesToUserTable(DbContext dbContext) { _dbContext = dbContext; } /// <inheritdoc /> protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Code", table: "User", type: "text", nullable: true);
migrationBuilder.AddColumn<string>( name: "By", table: "Users", type: "text", nullable: true);
migrationBuilder.CreateIndex( name: "IX_Code", table: "Users", column: "Code", unique: true) .Annotation("Npgsql:NullsDistinct", true);
migrationBuilder.CreateIndex( name: "IX_By", table: "Users", column: "By");
} /// <inheritdoc /> protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "Code", table: "Users");
migrationBuilder.DropIndex( name: "By", table: "Users");
migrationBuilder.DropColumn( name: "Code", table: "Users");
migrationBuilder.DropColumn( name: "By", table: "Users"); } private void UpdateReferralValuesForExistingUser() {
var usersCode = _dbContext.Users .Where(u => u.Code == null) .ToList();
foreach (var user in usersCode) { user.Code = GenerateUniqueCode(8); } _dbContext.SaveChanges(); //} } public string GenerateUniqueCode(int length) { if (length < 1) { throw new ArgumentException("Length must be greater than 0"); } Guid guid = Guid.NewGuid(); string base36 = Number.ConvertBase36(guid); if (base36.Length >= length) { return base36.Substring(0, length).ToUpper(); } else { Random random = new Random(); const string chars = "keys"; while (base36.Length < length) { base36 += chars[random.Next(chars.Length)]; } return base36.ToUpper(); } } } private readonly PvrpleShopDbContext _dbContext; /// <inheritdoc />
private void UpdateReferralValuesForExistingUser() { // var factory = new PvrpleShopDbContextFactory(); // using (var context = factory.CreateDbContext(null)) //{ var usersWithoutReferralCode = _dbContext.Users .Where(u => u.ReferralCode == null) .ToList();
foreach (var user in usersWithoutReferralCode) { user.ReferralCode = GenerateUniqueReferralCode(8); }
_dbContext.SaveChanges(); //} } public string GenerateUniqueReferralCode(int length) { if (length < 1) { throw new ArgumentException("Length must be greater than 0"); } Guid guid = Guid.NewGuid(); string base36String = NumberUtilities.ConvertToBase36(guid); if (base36String.Length >= length) { return base36String.Substring(0, length).ToUpper(); } else { Random random = new Random(); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; while (base36String.Length < length) { base36String += chars[random.Next(chars.Length)]; } return base36String.ToUpper(); } }
```