(标题已被更改,请参阅下面的编辑以获得更改)
目前的项目:
当我使用fluent API定义具有两个唯一索引的表时:
Property(x => x.UserId)
.HasColumnOrder(1)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.HasColumnAnnotation(
"UserId",
new IndexAnnotation(
new IndexAttribute("IX_UserId") {
IsUnique = true
}
)
)
.IsRequired();
Property(x => x.UserName)
.HasColumnOrder(2)
.HasColumnName("UserName")
.HasColumnType("nvarchar")
.HasMaxLength(256)
.HasColumnAnnotation(
"Username",
new IndexAnnotation(
new IndexAttribute("IX_Username") {
IsUnique = true
}
)
)
.IsRequired();
我在迁移文件中看到了正确的迁移条目:
UserId = c.Guid(
nullable: false,
identity: true,
defaultValueSql: "NEWID()",
annotations: new Dictionary<string, AnnotationValues> {
{
"UserId",
new AnnotationValues(
oldValue: null,
newValue: "IndexAnnotation: {
Name: IX_UserId,
IsUnique: True
}"
)
}
}
),
UserName = c.String(
nullable: false,
maxLength: 256,
annotations: new Dictionary<string, AnnotationValues> {
{
"Username",
new AnnotationValues(
oldValue: null,
newValue: "IndexAnnotation: {
Name: IX_Username,
IsUnique: True
}"
)
}
}
),
但是,当我检查数据库并查看表的键/索引时,我注意到UserId
索引没有命名为IX_UserId
(它被称为相当默认的PK_dbo.User
),而且UserName
根本不存在索引/唯一性。我需要在中手动创建它。
正如所述,虽然EF Fluent API能够创建看起来像正确的迁移文件,包含所有正确的属性,但这并没有转化为完全成功地迁移到DB,这只是必要的,因此创建了默认索引(迁移文件中指定的所有索引信息都被完全忽略,以支持主键的默认修饰)。
有人能解释我哪里出了问题吗?
编辑:
Hmmmm…刚碰到this other example,也许这就是我走错的地方?根据它,我的Fluent API应该是这样的:
Property(x => x.UserId)
.HasColumnOrder(1)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.HasColumnAnnotation(
"UserId",
new IndexAnnotation(
new IndexAttribute("IX_UserId") {
IsUnique = true,
Order = 1
}
)
)
.IsRequired();
Property(x => x.UserName)
.HasColumnOrder(2)
.HasColumnName("UserName")
.HasColumnType("nvarchar")
.HasMaxLength(256)
.HasColumnAnnotation(
"Username",
new IndexAnnotation(
new IndexAttribute(),
new IndexAttribute("IX_Username") {
IsUnique = true
Order = 2
}
)
)
.IsRequired();
我读对了另一篇文章吗?
编辑2:
啊哈…我刚刚发现正在使用正确的索引名,但只在其他表中这些键作为外键存在的地方使用。因此,在其他表中的UserId
作为外键存在的地方,它具有正确的IX_UserId
索引名,尽管我的Fluent API从未在该表中描述过该外键的索引。
威士忌。探戈。狐步舞。
编辑3:
Fluent API是而不是,它创建了正确的迁移文件。刚才将这些表的外键与迁移文件进行了比较,而其他表显然有以下内容:
.Index(t => t.UserId)
.Index(t => t.CourseId);
所以是的,Fluent API没有构建正确的迁移文件,因为它丢失了大量用于主键等的.Index()
条目。
发布于 2017-10-31 16:43:58
看看HasColumnAnnotation方法的文档,它说:
我猜您没有使用有效的C#/EDM注释名。尝试使用IndexAnnotation.AnnotationName
常量作为索引的参数:
using System.Data.Entity.Infrastructure.Annotations;
...
Property(x => x.UserId)
...
.HasColumnAnnotation(
IndexAnnotation.AnnotationName, <-- this is the valid annotation name.
new ndexAttribute("Ix_UserId") {IsUnique = true});
这是一个等于"Index"
的常量值,但我怀疑这可能是引发问题的原因。
希望这能有所帮助!
https://stackoverflow.com/questions/47039861
复制相似问题