到目前为止,我已经允许EF为我的项目自动生成索引和键名,但遗憾的是我开始在一个场景中达到字符限制。基本上我有两个带有聚簇键(4列)的表,需要在它们之间创建一个查找表。一旦我这样做,我得到错误:
"The identifier that starts with [Long FK Name Here] is too long. Maximum length is 128.
最好在Fluent API中,如何在Entity Framework 7中手动命名外键索引,使其不是FK_table2_table1_table1ID?例如,在下面的简单示例中,如何将FK从租户表FK_tbl_Person_tbl_Tenant_TenantID重命名为FK_Tenant?
答案 0 :(得分:0)
我已经使用本教程使用VS2015安装EF:
EF - Console Application to New Database
基本上:
我创建了一个包含两个实体的简单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");
然后,您需要使用程序包管理器控制台为您的上下文创建迁移:
最后使用程序包管理器控制台更新数据库:
使用Sql Server Management Studio,我可以检查索引的名称: