2016-01-26 36 views
1

到目前为止,我已经允许EF为我的项目自动生成索引和键名称,但不幸的是我开始在一种情况下达到字符限制。基本上我有两个具有集群键(4列)的表,并且需要在它们之间创建一个查找表。一旦我这样做寿,我得到的错误:在Entity Framework Core 1.0中,您如何重新命名索引?

"The identifier that starts with [Long FK Name Here] is too long. Maximum length is 128. 

最好是在流利的API,我怎么能手动命名实体框架7的外键索引所以它不是FK_table2_table1_table1ID?例如,在我下面的简单示例中,如何将FK从租户表FK_tbl_Person_tbl_Tenant_TenantID重命名为FK_Tenant?

enter image description here

+0

您使用的是什么版本的EntityFramework? – Rob

+0

实体框架7但大部分东西在6似乎工作.. – chris

+0

它不重复EF核心有完全不同的API。 –

回答

0

我用这个教程使用VS2015安装EF:

EF - Console Application to New Database

基本上是:

  • 确保您的目标的.NET Framework 4.5.1或更高版本。
  • 确保您使用的是最新版本的nuget package manager
  • 安装这两个包:
    • EntityFramework.MicrosoftSqlServer - 预
    • EntityFramework.Commands - 预

我我们创建了一个简单的DbContext,其中包含两个实体:

using Microsoft.Data.Entity; 
using System.Collections.Generic; 
public class SampleContext : DbContext 
{ 
    public DbSet<Person> People { get; set; } 

    public DbSet<Tenant> Tenants { get; set; } 

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
     // Visual Studio 2015 | Use the LocalDb 12 instance created by Visual Studio 
     optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"); 

     // Visual Studio 2013 | Use the LocalDb 11 instance created by Visual Studio 
     // optionsBuilder.UseSqlServer(@"Server=(localdb)\v11.0;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"); 
    } 

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     // Configure the name of the foreign key 
     modelBuilder.Entity<Person>() 
      .HasOne(p => p.Tenant) 
      .WithMany(t => t.Persons) 
      .HasConstraintName("MyForeignKey"); 

     // Configure the name of a unique index 
     modelBuilder.Entity<Person>().HasAlternateKey(p => p.Email).ForSqlServerHasName("MyUniqueEmail"); 

    } 
} 

public class Person 
{ 
    public int PersonId { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public virtual Tenant Tenant { get; set; } 
} 

public class Tenant 
{ 
    public Tenant() 
    { 
     Persons = new HashSet<Person>(); 
    } 

    public int TenantId { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Person> Persons { get; set; } 
} 

所以配置外键的名称:

modelBuilder.Entity<Person>() 
      .HasOne(p => p.Tenant) 
      .WithMany(t => t.Persons) 
      .HasConstraintName("MyForeignKey"); 

要配置一个唯一索引的名称:

modelBuilder.Entity<Person>().HasAlternateKey(p => p.Email).ForSqlServerHasName("MyUniqueEmail"); 

这时就需要使用包来创建迁移您的上下文Manager控制台:

  • 附加迁移MyFirstMigration

最后更新使用软件包管理器控制台数据库:

  • 更新,数据库

使用SQL Server Management Studio中,我可以检查我的索引的名字:

enter image description here

相关问题