简体   繁体   中英

How make Entity Framework 6 use default value from SQL SEQUENCE

I have created the following SQL SEQUENCE

CREATE SEQUENCE SEQ_ORDENES_TRABAJO as int START WITH 1 INCREMENT BY 1 MINVALUE 1 CYCLE ;

That is used in this table to allow the 'Consecutivo' field to use that SEQUENCE

CREATE TABLE [adm].[OrdenesTrabajo](
    [Id] [uniqueidentifier] NOT NULL,
    [Consecutivo] [int] NOT NULL,
    [FechaIngreso] [datetime] NOT NULL,
    [RemolcadorId] [uniqueidentifier] NOT NULL,
    [Justificacion] [nvarchar](1000) NOT NULL,
    [Prioridad] [smallint] NOT NULL,
    [EstadoMantenimientoId] [uniqueidentifier] NOT NULL,
    [Usuario] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_adm.OrdenesTrabajo] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [adm].[OrdenesTrabajo] ADD  CONSTRAINT [OT_consecutivoConstraint]  DEFAULT (NEXT VALUE FOR [SEQ_ORDENES_TRABAJO]) FOR [Consecutivo]
GO

And this is the Entity Framework class that matches that table

[Table("adm.OrdenesTrabajo")]
public class OrdenTrabajo
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public Int32 Consecutivo { get; set; }

    [Required]
    public DateTime FechaIngreso { get; set; }

    [Required]
    public Guid RemolcadorId { get; set; }

    [Required]
    [MaxLength(1000)]
    public String Justificacion { get; set; }

    [Required]
    public Int16 Prioridad { get; set; }

    [Required]
    public Guid EstadoMantenimientoId { get; set; }

    [Required]
    public String Usuario { get; set; }

    [ForeignKey("RemolcadorId")]
    public Equipo Remolcador { get; set; }

    [ForeignKey("EstadoMantenimientoId")]
    public EstadoMantenimiento EstadoMantenimiento { get; set; }
}

When I use a script that omits the 'Consecutivo' field in the INSERT commands it works as expected and takes the value from the SEQUENCE.

How can I make Entity Framework 6 use that default value for the 'Consecutivo' column when inserting the entity ?

Is it my only option to create a Stored Procedure with the INSERT clause and call that from Entity Framework ?

Turns out that I needed was a single line specifying that is a DatabaseGenerated column

    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public Int32 Consecutivo { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM