EF Core: How to: Database generated string with specific rules?

流过昼夜 提交于 2019-12-13 03:47:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!