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;
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);
}
[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
CorrespondenceAddress = CorrespondenceAddress
AddressLine1 = {string} "TestAddress"
AddressLine2 = {string} null
AddressLine3 = {string} null
AddressLine4 = {string} null
Id = {int} 0
4 Replies
sibber
sibber5mo ago
those 2 attributes on Id are implicit whats Policy
ミ★ 𝘢𝘣𝘤𝘥𝘦𝘧𝘩 ★彡
It's okay I got it resolved with the following added to the OnModelCreate instead modelBuilder.Entity<CorrespondenceAddress>().Property(c => c.Id).HasDefaultValue(0);
canton7
canton75mo ago
$close
MODiX
MODiX5mo ago
If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server