Invalid C # EF6 Index Attribute

I am trying to combine two fields into a unique index with EF6. But the update-database command will not add the Owner field to the index. I think about it because it is not a primitive type, but FK, but I'm not sure how to fix it.

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

Generated Indexes:

CREATE A UNIQUE CONTINUOUS INDEX [IX_FundIdentifierAndOwner] ON [dbo]. [Funds] ([Identifier] ASC);

CREATE A UNIQUE CONTINUOUS INDEX [IX_FundNameAndOwner] ON [dbo]. [Funds] ([Name] ASC);

CREATE UNSPECIFIED INDEX [IX_Owner_Id] ON [dbo]. [Funds] ([Owner_Id] ASC);

Any help is much appreciated!

+5
source share
1 answer

When creating a navigation property (link to another table), you must specify the column name to use as a foreign key. If you do not, EF assumes that it is a column named Objectname_Id.

You can see in the sql code that he called your column [Owner_Id]. The problem is that when you do this this way, you cannot control the data annotations for this column.

try it

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

Adding a column named ObjectId (or Objec_Id) EF by convention understands that the column is for the property owner.

This is the script generated by the migration:

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

Here is an explanation of the standard code first conventions .

+2
source

All Articles