Entity Framework 6: Multicolumn unique index featuring navigation property

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

Question

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.

1
6
1/17/2015 10:02:35 AM

Accepted Answer

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

8
1/17/2015 11:23:35 AM


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