警告
This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef. 本文档是基于EF7版本.对于EF6.x及更早的版本请参见 http://msdn.com/data/ef.
注解
This article uses EF 7.0.0-rc1 which is the latest pre-release available on NuGet.org. You can find nightly builds of the EF7 code base hosted on https://www.myget.org/F/aspnetvnext/ but we do not maintain up-to-date documentation for nightly builds.
注解
The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared EntityFramework.Relational package).
Sequences¶
A sequence generates a sequential numeric values in the database. Sequences are not associated with a specific table.
Conventions¶
By convention, sequences are not introduced in to the model.
Data Annotations¶
You can not configure a sequence using Data Annotations.
Fluent API¶
You can use the Fluent API to create a sequence in the model.
1 2 3 4 5 6 7 8 9 10 11 | class MyContext : DbContext
{
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasSequence<int>("OrderNumbers");
}
}
public class Order
|
You can also configure additional aspect of the sequence, such as its schema, start value, and increment.
1 2 3 4 5 6 7 8 9 10 11 | class MyContext : DbContext
{
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasSequence<int>("OrderNumbers", schema: "shared")
.StartsAt(1000)
.IncrementsBy(5);
}
}
|
Once a sequence is introduced, you can use it to generate values for properties in your model. For example, you can use Default Values to insert the next value from the sequence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class MyContext : DbContext
{
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasSequence<int>("OrderNumbers", schema: "shared")
.StartsAt(1000)
.IncrementsBy(5);
modelBuilder.Entity<Order>()
.Property(o => o.OrderNo)
.HasDefaultValueSql("NEXT VALUE FOR shared.OrderNumbers");
}
}
public class Order
{
public int OrderId { get; set; }
public int OrderNo { get; set; }
public string Url { get; set; }
}
|