我正在尝试为 Entity Framework 7 创建代码优先模型。我正在使用最近发布的 Visual Studio 2015 Beta 和以下版本的 EntityFramework 包(来自我的 project.json 文件的片段):
"EntityFramework.SqlServer": "7.0.0-beta1",
"EntityFramework.Commands": "7.0.0-beta1",
看起来目前没有可用的数据注释,我正在使用 OnModelCreating 覆盖和最近实现的(部分?)迁移来创建我的模型。
目前,主键和一对一关系以及为整数类型创建索引都有效。例如:
builder.Entity<Article>(e =>
{
e.Key(c => c.Id);
e.OneToOne<Category>(c => c.Category);
e.Index(c => c.Time).IsUnique(false);
});
此代码段会生成以下迁移代码:
migrationBuilder.CreateTable("Article",
c => new
{
Id = c.String(),
// ...
CategoryIdKey = c.Int(nullable: false),
Time = c.DateTime(nullable: false),
// ...
})
.PrimaryKey("PK_Article", t => t.Id)
.UniqueConstraint("UC_Article_CategoryIdKey", t => t.CategoryIdKey);
migrationBuilder.AddForeignKey("Category", "FK_Category_Article_CategoryId", new[] { "CategoryId" }, "Article", new[] { "CategoryIdKey" }, cascadeDelete: false);
migrationBuilder.CreateIndex("Article", "IX_Article_Time", new[] { "Time" }, isUnique: false, isClustered: false);
但是当我尝试将索引添加到字符串属性时,会生成迁移,但是当应用时被 SQL Server 拒绝,显然是由于列类型为 nvarchar(MAX)。似乎.Required().MaxLength(100)
不强制生成有限的字符串列类型。尽管有一种方法可以更改列类型,但我似乎找不到通过 ModelBuilder 调用它的方法:
builder.Entity<Keyword>(e =>
{
e.Key(c => c.Id);
e.Property(c => c.Word).Required().MaxLength(100);
e.Index(c => c.Word).IsUnique(true);
});
产生的迁移:
migrationBuilder.CreateTable("Keyword",
c => new
{
Id = c.Int(nullable: false, identity: true),
Word = c.String(nullable: false, maxLength: 100)
})
.PrimaryKey("PK_Keyword", t => t.Id);
migrationBuilder.CreateIndex("Keyword", "IX_Keyword_Word", new[] { "Word" }, isUnique: true, isClustered: false);
有没有办法在 EF7 的 beta 版本中创建字符串属性的索引?