How make Entity Framework 6 use default value from SQL SEQUENCE

c# entity-framework entity-framework-6 sql-server

Question

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 ?

1
2
3/14/2016 1:53:52 PM

Popular Answer

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

    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public Int32 Consecutivo { get; set; }
1
3/14/2016 8:43:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow