C#EF6索引属性不起作用

时间:2015-08-21 14:39:22

标签: c# entity-framework ef-code-first

我正在尝试将两个字段组合成一个带有EF6的唯一索引。但update-database命令不会将“Owner”字段添加到索引中。我在想它是因为它不是原始类型而是FK,但我不确定如何解决它。

public class Fund
{
    [Key]
    public int FundId { get; set; }

    [Required]
    [Index("IX_FundNameAndOwner", IsUnique = true, Order = 1)]
    [Index("IX_FundIdentifierAndOwner", IsUnique = true, Order=1)]
    public ApplicationUser Owner { get; set; }


    [Required]
    [Index("IX_FundNameAndOwner", IsUnique = true, Order=2)]
    [MaxLength(25)]
    public string Name { get; set; }

    [Required]
    [Index("IX_FundIdentifierAndOwner", IsUnique = true, Order=2)]
    [MaxLength(25)]
    public string Identifier { get; set; }

    public double Balance { get; set; }
}

生成的索引:

  

创建独特的非集群索引[IX_FundIdentifierAndOwner]       ON [dbo]。[Funds]([Identifier] ASC);

     

创建独特的非集群索引[IX_FundNameAndOwner]       ON [dbo]。[Funds]([Name] ASC);

     

创建非集群索引[IX_Owner_Id]       ON [dbo]。[Funds]([Owner_Id] ASC);

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

创建导航属性(引用另一个表)时,应指定要用作外键的列名。如果你不这样做,EF假定它是一个名为Objectname_Id的列。

您可以在sql代码中看到它调用了您的列[Owner_Id]。问题是,当您这样做时,您无法控制该列的数据注释。

试试这个

public class Fund
{
    [Key]
    public int FundId { get; set; }

    [Required]
    [Index("IX_FundNameAndOwner", IsUnique = true, Order = 1)]
    [Index("IX_FundIdentifierAndOwner", IsUnique = true, Order = 1)]
    public int OwnerId { get; set; } // <---- ADD THIS!

    public virtual ApplicationUser Owner { get; set; }


    [Required]
    [Index("IX_FundNameAndOwner", IsUnique = true, Order = 2)]
    [MaxLength(25)]
    public string Name { get; set; }

    [Required]
    [Index("IX_FundIdentifierAndOwner", IsUnique = true, Order = 2)]
    [MaxLength(25)]
    public string Identifier { get; set; }

    public double Balance { get; set; }
}

添加名为ObjectId(或Objec_Id)的列EF按惯例理解该列是属性所有者。

这是迁移生成的脚本:

CREATE TABLE [dbo].[Funds] (
    [FundId] [int] NOT NULL IDENTITY,
    [OwnerId] [int] NOT NULL,
    [Name] [nvarchar](25) NOT NULL,
    [Identifier] [nvarchar](25) NOT NULL,
    [Balance] [float] NOT NULL,
    CONSTRAINT [PK_dbo.Funds] PRIMARY KEY ([FundId])
)
CREATE UNIQUE INDEX [IX_FundIdentifierAndOwner] ON [dbo].[Funds]([OwnerId], [Identifier])
CREATE UNIQUE INDEX [IX_FundNameAndOwner] ON [dbo].[Funds]([OwnerId], [Name])

以下是默认Code First Conventions的解释。