简体   繁体   中英

The right way to add indexes for Entity Framework code-first applications?

I've been researching quite a while on how to add indexes on columns, when you work with Entity Framework code-first.

As I see it, there are three methods:

  1. Add them in the actual migrations (after EF 4.2)
  2. Use the new IndexAttribute in EF 6.1
  3. Add indexes to columns directly

I am not very fond of either method as:

1: Seems to be quite risky. Sometimes you might want to reset all migrations and make an "Initial setup" again. Then your indexes might be deleted.

In addition I think it's very little transparent and hidden quite well.

2: Seems quite new and limited documentation. Not sure how well this works?

3: Dangerous if you re-create the database.

So my question is: how do you add indexes in Entity Framework code-first?

  1. Manually adding code in migrations is OK but I wouldn't recommend it. You still need to update your model anyway so do migrations properly

  2. What makes you think this is new and undocumented? There's absolutely nothing wrong with this.

  3. Definitely don't do this. The temptation to manually cludge the database shoudl be avoided.

  4. You didn't mention this, but you can also use the fluent syntax, something like this:

     modelBuilder .Entity<Company>() .Property(t => t.Name) .HasColumnAnnotation( "Index", new IndexAnnotation(new IndexAttribute("IX_Company_Name") { IsUnique = true })); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM