Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6: Multicolumn unique index featuring navigation property

How can I set multicolumn index on model like that:

public class Meta
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public Guid Id { get; set; }

    [Index("MetaPeriodDateUnq", IsUnique = true, Order = 2)]
    [Required] 
    public DateTime Date { get; set; }

    [Index("MetaPeriodDateUnq", IsUnique = true, Order = 1)]
    [Required] 
    public virtual PeriodType Period { get; set; }

    /*
    ...
    */
}

public class PeriodType
{
    [Key]
    public Guid Id { get; set; }

    /*
    ...
    */
}

After DB initialization there is only "MetaPeriodDateUnq" index mentioning Meta.Date column, but I'm relying on Meta.Date + Meta.Period.Id uniqueness.

like image 328
Sergey Prytkov Avatar asked Jan 17 '15 10:01

Sergey Prytkov


1 Answers

You must include the foreign key explicitly, annotations on navigation properties do generally not work.

[Index("MetaPeriodDateUnq", IsUnique = true, Order = 2)]
public DateTime Date { get; set; }

[Index("MetaPeriodDateUnq", IsUnique = true, Order = 1)]
public Guid PeriodId { get; set; }

public virtual PeriodType Period { get; set; }

This should work (not tested).

like image 118
Axel Heer Avatar answered Sep 17 '22 23:09

Axel Heer