Entity Framework Core Create Unique Index on DateTime?

c# entity-framework-core

Question

[Table("hProducaoRegistos", Schema = "Robotics")]
public class ProducaoRegisto
{
    public ProducaoRegisto()
    {
        DataCriacao = DateTime.Now;
    }

    public int Id { get; set; }
    [Display(Name = "Criado Por")]
    public int Operador { get; set; }
    [Display(Name = "Criado Em")]

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
    public DateTime DataCriacao { get; set; }                
    public int CelulaId { get; set; }
    public Celula Celula { get; set; }
    public int TurnoId { get; set; }
    public Turno Turno { get; set; }

    public virtual ICollection<CheckListRegisto> CheckListRegistos { get; set; }
    public virtual ICollection<ProcessoRegisto> ProcessoRegistos { get; set; }
    public virtual ICollection<DefeitoRegisto> DefeitoRegistos { get; set; } 
}

I want to have only a record unique by day, how can I do this using EF7? The objective is to make the user create a record only once per day until midnight of next day.

1
0
7/29/2019 6:47:09 PM

Accepted Answer

I don't know about filtering by the 'day number', but if you want a Date column with a unique constraint:

With the fluent API

builder.HasIndex(e => e.CreatedDate)
       .IsUnique();
builder.Property(e => e.CreatedDate)
       .HasColumnType("Date");

With data annotations

[Index(IsUnique=true)]
[Column(TypeName="Date")]
public DateTime CreatedDate { get; set; }
1
7/29/2019 4:54:35 PM

Popular Answer

  1. use timestamp or
  2. use default identity beside the date column and use linq to select specific day as you want


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