# Troubleshooting: EF Core Pending Model Changes Warning

## Issue Description

When deploying Jellyfin to a test/production environment, you may encounter this error:

```
System.InvalidOperationException: The model for context 'JellyfinDbContext' has pending changes. 
Add a new migration before updating the database.
```

This error occurs when Entity Framework Core detects that the database model has changed but there isn't a corresponding migration file.

## Root Causes

### 1. Missing Migration Files (Most Common)
The development machine has all the migration files, but they weren't deployed to the test/production machine.

**Solution**: Ensure all migration files are deployed with your application.

#### Check for Migration Files

**Location:** `src/Jellyfin.Database/Jellyfin.Database.Providers.Postgres/Migrations/`

Files should include:
- `*.cs` - Migration classes
- `*.Designer.cs` - Migration metadata
- `JellyfinDbContextModelSnapshot.cs` - Current model snapshot

**Verify on test machine:**
```bash
# Check if migration files exist
ls /opt/pgsql-jellyfin/src/Jellyfin.Database/Jellyfin.Database.Providers.Postgres/Migrations/

# Count migration files
find /opt/pgsql-jellyfin -name "*Migration*.cs" | wc -l
```

### 2. Build Configuration Mismatch
Migration files might be excluded from the build output.

**Solution:** Check your `.csproj` file:

```xml
<ItemGroup>
  <!-- Ensure migrations are included -->
  <Compile Include="Migrations\*.cs" />
</ItemGroup>
```

### 3. Model Changed Without Migration
The code has model changes that haven't been captured in a migration.

**Solution:** Generate a new migration on your development machine:

```bash
# Navigate to the project directory
cd src/Jellyfin.Database/Jellyfin.Database.Providers.Postgres/

# Create a new migration
dotnet ef migrations add YourMigrationName --context JellyfinDbContext

# Rebuild and redeploy
dotnet build
```

### 4. Different .NET SDK Versions
Different SDK versions might have different EF Core behaviors.

**Solution:** Ensure both machines use the same .NET SDK version:

```bash
# Check version
dotnet --version

# Should be .NET 11 or later
```

## Fix Applied in Code

We've suppressed the `PendingModelChangesWarning` in the database provider configuration since we explicitly handle migrations in our startup code:

### PostgreSQL Provider
```csharp
options
    .UseNpgsql(connectionString, options => /* ... */)
    .ConfigureWarnings(warnings =>
        warnings.Ignore(RelationalEventId.PendingModelChangesWarning));
```

### SQLite Provider
```csharp
options
    .UseSqlite(connectionString, options => /* ... */)
    .ConfigureWarnings(warnings =>
    {
        warnings.Ignore(RelationalEventId.NonTransactionalMigrationOperationWarning);
        warnings.Ignore(RelationalEventId.PendingModelChangesWarning);
    });
```

## Verification Steps

### 1. Check Logs on Test Machine

Look for these log messages:

```
[INF] Checking PostgreSQL database for missing tables...
[INF] Found X pending migrations: Migration1, Migration2, ...
[INF] Applying migrations...
[INF] Successfully applied X migrations
```

If you see warnings:
```
[WRN] Model has pending changes. This may indicate missing migration files.
[WRN] If you're seeing this on a test/production system, ensure all migration files are deployed.
```

### 2. Compare Migration Files

**On development machine:**
```powershell
# PowerShell
Get-ChildItem -Path "src\Jellyfin.Database\Jellyfin.Database.Providers.Postgres\Migrations" -Recurse | Select-Object Name
```

**On test machine:**
```bash
# Linux
find /opt/pgsql-jellyfin/src/Jellyfin.Database/Jellyfin.Database.Providers.Postgres/Migrations -type f
```

The file lists should match!

### 3. Verify Deployment

Ensure your deployment process includes:

1. **All .cs files** in Migrations folder
2. **All .Designer.cs files** in Migrations folder
3. **JellyfinDbContextModelSnapshot.cs**

## Deployment Checklist

### For Manual Deployment

- [ ] Build the solution in Release mode
- [ ] Copy all migration files from dev to test machine
- [ ] Verify file permissions (migrations must be readable)
- [ ] Check that the migration assembly is correct
- [ ] Restart Jellyfin after deploying new files

### For Docker/Container Deployment

Ensure your `Dockerfile` includes:

```dockerfile
# Copy migration files
COPY src/Jellyfin.Database/Jellyfin.Database.Providers.Postgres/Migrations/ \
     /app/src/Jellyfin.Database/Jellyfin.Database.Providers.Postgres/Migrations/
```

### For CI/CD Deployment

```yaml
# Example GitHub Actions / GitLab CI
- name: Build
  run: dotnet build --configuration Release

- name: Publish
  run: dotnet publish --configuration Release --no-build

# Verify migrations are included
- name: Verify Migrations
  run: |
    if [ ! -d "publish/Migrations" ]; then
      echo "ERROR: Migration files not found in publish output!"
      exit 1
    fi
```

## Alternative: Database-First Approach (Not Recommended)

If you absolutely cannot deploy migration files, you could manually create the database schema, but this is **not recommended** as it bypasses EF Core's migration tracking.

## Quick Fix for Immediate Issue

If you need an immediate fix on the test machine:

### Option 1: Deploy Missing Files (Recommended)

1. Copy migration files from development machine to test machine
2. Restart Jellyfin
3. Verify migrations are applied

### Option 2: Temporarily Skip Migration Check (Not Recommended)

You could modify the code to skip the check, but this could lead to database inconsistencies:

```csharp
// In EnsureTablesExistAsync - NOT RECOMMENDED
if (pendingMigrationsList.Count > 0)
{
    logger.LogWarning("Skipping {Count} pending migrations", pendingMigrationsList.Count);
    // Don't call MigrateAsync
}
```

## Prevention

### 1. Automated Deployment

Use a deployment script that ensures all files are copied:

```bash
#!/bin/bash
# deploy.sh

SOURCE_DIR="/path/to/dev"
DEST_DIR="/opt/pgsql-jellyfin"

# Stop Jellyfin
systemctl stop jellyfin

# Copy binaries and migrations
rsync -av --include='*.dll' --include='*.cs' --include='*.Designer.cs' \
    "${SOURCE_DIR}/" "${DEST_DIR}/"

# Verify migrations
if [ ! -f "${DEST_DIR}/src/Jellyfin.Database/Jellyfin.Database.Providers.Postgres/Migrations/JellyfinDbContextModelSnapshot.cs" ]; then
    echo "ERROR: Migration files not found!"
    exit 1
fi

# Start Jellyfin
systemctl start jellyfin
```

### 2. Continuous Integration

Add migration verification to your build pipeline:

```yaml
test:
  script:
    - dotnet build
    - dotnet test
    # Verify migrations compile
    - dotnet ef migrations list --project src/Jellyfin.Database/Jellyfin.Database.Providers.Postgres/
```

### 3. Version Control

Always commit migration files:

```bash
git add src/Jellyfin.Database/Jellyfin.Database.Providers.Postgres/Migrations/
git commit -m "Add database migration"
git push
```

## Related Files Modified

To fix this issue, we modified:

1. **PostgresDatabaseProvider.cs** - Added warning suppression
2. **SqliteDatabaseProvider.cs** - Added warning suppression
3. **Both providers** - Improved error logging and diagnostics

## Testing the Fix

After applying the code changes:

1. **Build the solution:**
   ```bash
   dotnet build
   ```

2. **Deploy to test machine**

3. **Check logs:**
   ```bash
   journalctl -u jellyfin -f
   # or
   tail -f /var/log/jellyfin/log_*.txt
   ```

4. **Verify startup:**
   - Should see "Checking PostgreSQL database for missing tables..."
   - Should NOT see "pending changes" error
   - Should see "Successfully applied X migrations" or "No migrations needed"

## Summary

The error was caused by EF Core's strict validation of model changes. We've:

✅ **Suppressed the warning** since we explicitly handle migrations  
✅ **Added better logging** to diagnose issues  
✅ **Improved error messages** to help identify root causes  
✅ **Maintained backward compatibility**  

The fix ensures that the automatic migration system works correctly without false positives from EF Core's model validation.
