EF - Cannot insert the value NULL into column 'Id'

I have this entity:

public class Address
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; init; }

    public required string AddressLine1 { get; init; }
    
    public string? AddressLine2 { get; init; }
    
    public string? AddressLine3 { get; init; }

    public string? AddressLine4 { get; init; }
    
}

public class RiskAddress : Address;

public class CorrespondenceAddress : Address;


I try to autofixture excluding the id but i dont think that works because its int so it will always default to 0 ? - fact check me pls

but the db should be handling generating its id, why do i get this error running the following test ?

[Fact]
    public async Task CanSaveEntityAsyncManual()
    {
        var policy2 = await SetupPolicyHybrid();
        await _dbContext.Policies.AddAsync(policy2);
        await _dbContext.SaveChangesAsync();

        List<Policy> savedPolicies = await _dbContext.Policies.ToListAsync();

        Assert.Equal(1, savedPolicies.Count);
    }


Microsoft.Data.SqlClient.SqlException Cannot insert the value NULL into column 'Id', table 'pas.dbo.CorrespondenceAddress'; column does not allow nulls. INSERT fails.

and here is the live auto fixtured entity copied in rider:
CorrespondenceAddress = CorrespondenceAddress
 AddressLine1 = {string} "TestAddress"
 AddressLine2 = {string} null
 AddressLine3 = {string} null
 AddressLine4 = {string} null
 Id = {int} 0
Was this page helpful?