【问题标题】:How to set starting value for an Identity primary key in Entity Framework code first?如何首先在实体框架代码中设置身份主键的起始值?
【发布时间】:2019-02-21 18:16:31
【问题描述】:

在我的项目中,我首先使用实体​​框架代码创建Appointments 表。当我将整数主键AppointmentNo 设置为[Key][Required] 时,它会创建初始主键以1 开头的表。

我希望约会号码从 1000 开始。我的数据库是 SQL Server。请帮我。先感谢您。

[DataContract]
public class Appointment
{
    [DataMember]
    [Key]
    [Required]
    public int AppointmentNo { get; set; }

    [DataMember]
    [Required]
    public string DoctorUN { get; set; }

    [DataMember]
    [Required]
    public string PatientUN { get; set; }
}

【问题讨论】:

标签: c# .net sql-server entity-framework-6 code-first


【解决方案1】:

不能使用ef注解,但是可以在迁移UP方法中执行sql

Sql("DBCC CHECKIDENT ('Appointment', RESEED, 1000)");

【讨论】:

  • 我从 SQL Server Management Studio 创建了表,并在执行代码之前在那里使用了您的查询,这样就完成了工作。谢谢
【解决方案2】:

EF 核心 3.1 您可以在更新数据库之前打开迁移脚本并对其进行编辑。 EF 为标识列创建此行: .Annotation("SqlServer:Identity", "1, 1"),

您可以将其更新为您想要的任何内容:

.Annotation("SqlServer:Identity", "你的起始值,你的增量值"),

示例:如果我希望 tblOrder 上的 OrderId 列从 1000 开始并递增 1:

migrationBuilder.CreateTable(
    name: "tblOrder",
    schema: "dbo",
    columns: table => new
    {
        OrderID = table.Column<int>(nullable: false)
            .Annotation("SqlServer:Identity", "1000, 1"),        
        CDate = table.Column<DateTime>(nullable: false, defaultValueSql: "getdate()")
    },
.
.
.

【讨论】:

    【解决方案3】:

    只要主键属性的类型是数字或 GUID,Code First 就会按照惯例自动将键配置为标识列。

    来自:EF and identity columns

    【讨论】:

    • 但是有没有办法将起始值设置为特定值并从该点开始递增?
    • 从文档中不清楚。不过之后很容易修复。和一个很好的反对代码的论据。 (点燃!)
    • 在回答之前仔细阅读问题
    猜你喜欢
    • 1970-01-01
    • 2011-11-07
    • 2023-03-23
    • 2015-09-02
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    相关资源
    最近更新 更多