问题
I have the following code first entity:
class Role
{
[Key]
public int Id { get; set; }
[Index("NameIndex", IsUnique = true)]
public string Name { get; set; }
}
But on checking the database with SQL Management Studio, there are multiple rows of the same name:
ID=1, Name=admin
ID=2, Name=admin
My context is very simple:
class MemberContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
}
Checking the SQL 2014 Express database table indexes, none are generated (only the PK exists).
Is there anything I have not done that is required for Index to work?
回答1:
So I was writing a new class (that was being injected from a DLL by Autofac) and the main program was running EF 6.0 (whereas my utility class project was using EF 6.1).
Specifically, I had to put a length constraint on the string length otherwise i wouldn't be able to put an index on it (indexes cannot be generated on varchar(max)):
class Role
{
[Key]
public int Id { get; set; }
[MaxLength(127)]
[Index(IsUnique = true)]
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
回答2:
I think your database has already been created and now you are trying to change the model. I could tell you to just delete the database and re-run you code, but this would mean losing all your data.
You should really read about EF Migrations and then implement it.
However, you will still have an issue. In that your existing data cannot be upgraded because of the new uniqueness constraint on Name.
UPDATE 1
On re-reading your question, "there are multiple rows of the same username". You show us the code for Role NOT Users. Have you applied the constraint to Users?
UPDATE 2
If you're cool to loose data, then do context.Database.Initialize(true);
in your startup logic.
来源:https://stackoverflow.com/questions/23710647/ef-6-1-index-isunique-not-being-generated