Entity Framework 6: a unique unique multi-loop index with a navigation property

How to set a multicolumn index for a model as follows:

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 initializing the DB, there is only the MetaPeriodDateUnq index that mentions the Meta.Date column, but I rely on the uniqueness of Meta.Date + Meta.Period.Id.

+4
source share
1 answer

You must explicitly specify a foreign key, annotations on navigation properties do not work at all.

[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 verified).

+6
source

All Articles