Support by-convention OnAdd for value-converted keys
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
In recent releases, we improved EF's ability to deal with value-converted keys, e.g. allowing users to define SQL Server identity columns even though the property CLR type isn't numeric.
However, the experience is still lacking; in the below sample, a value converter is defined via pre-convention configuration, but the property isn't configured as an identity column; this is because the property doesn't have ValueGenerated.OnAdd on it. If the value converter is configured on the property specifically this works, and of course, a non-value-converted CLR property (int/long) works as well.
/cc @AndriySvyryd
```c#
await using var context = new BlogContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();
public class BlogContext : DbContext
{
public DbSet Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false")
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
configurationBuilder
.Properties()
.HaveConversion();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// The following isn't essential to the issue, but should also work:
// modelBuilder.UseIdentityColumns(seed: 5);
}
public class AddressIdValueConverter() : ValueConverter(v => v.Raw, v => new(v));
}
public class Blog
{
public BlogId Id { get; set; }
public string Name { get; set; }
}
public struct BlogId(long raw)
{
public long Raw { get; } = raw;
}
```
Contributor guide
Assessment
This issue has not been assessed yet.