【问题标题】:Entity Framework 6: Multicolumn unique index featuring navigation property实体框架 6:具有导航属性的多列唯一索引
【发布时间】:2015-01-17 10:02:35
【问题描述】:

如何在这样的模型上设置多列索引:

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

    /*
    ...
    */
}

数据库初始化后,只有“MetaPeriodDateUnq”索引提及 Meta.Date 列,但我依赖 Meta.Date + Meta.Period.Id 唯一性。

【问题讨论】:

    标签: c# sql entity-framework sql-server-2008 entity-framework-6


    【解决方案1】:

    您必须明确包含外键,导航属性上的注释通常不起作用。

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

    这应该可以工作(未经测试)。

    【讨论】:

    • 如果您想保留默认的 EF 命名,Guid PeriodId 将被命名为 Periods_PeriodId
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多