问题
Is it possible with the fluent api to create a database generated string with specific rules?
Like say: The string should start with "a" then a number that is incremented by 1 and minimum starting value is 10000.
e.g. a10001, a10002,...
回答1:
You could use a combination of HasSequence
and HasDefaultValueSql
Example works in SQL Server, not sure about other providers.
public class Foo
{
public int FooId { get; set; }
public string GeneratedString { get; set; }
}
public class FooContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.HasSequence<int>("GeneratedStringSequence")
.StartsAt(10000)
.IncrementsBy(1);
modelBuilder
.Entity<Foo>()
.Property(f => f.GeneratedString)
.HasDefaultValueSql("FORMAT((NEXT VALUE FOR GeneratedStringSequence), 'a#')");
}
}
来源:https://stackoverflow.com/questions/56443761/ef-core-how-to-database-generated-string-with-specific-rules