实体框架核心是否在DateTime上创建唯一索引?

时间:2019-07-29 14:02:39

标签: c# entity-framework-core

[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; } 
}

我只希望每天有一条唯一记录,如何使用EF7来做到这一点?目的是使用户每天只创建一次记录,直到第二天午夜为止。

3 个答案:

答案 0 :(得分:1)

我不知道如何通过“天数”进行过滤,但是如果您想要具有唯一约束的Date列:

使用流畅的API

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

带有数据注释

[Index(IsUnique=true)]
[Column(TypeName="Date")]
public DateTime CreatedDate { get; set; }

答案 1 :(得分:0)

您可以创建一个表示日期的int并将其用作主键。 DateTime类具有Day属性,可以让您以整数表示日期。

答案 2 :(得分:0)

  1. 使用时间戳记或
  2. 使用日期列旁边的默认标识,并使用linq选择所需的特定日期