我有这个问题,我想在整数和字符串之间创建一个唯一的索引,但它给了我以下问题。我怎样才能完成这项工作?为什么不允许这样做?因为我实际上真的想要这个独特的组合,以确保数据库中没有存储双标签。
表'dbo.HostingReportGroups'中的列'Label'的类型无效,无法用作索引中的键列。
我用于此的模型如下:
public class HostingReportGroup
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Index("UniqueCustomerAndLabel", 1, IsUnique = true)]
public int CustomerId { get; set; }
[Index("UniqueCustomerAndLabel", 2, IsUnique = true)]
public string Label { get; set; }
public virtual ICollection<HostingReportGroupList> HostingReportGroupLists { get; set; }
}
我正在尝试执行的迁移包含以下代码:
public partial class adding_unique_key_to_hosting_report_group : DbMigration
{
public override void Up()
{
CreateIndex("dbo.HostingReportGroups", new[] { "CustomerId", "Label" }, unique: true, name: "UniqueCustomerAndLabel");
}
public override void Down()
{
DropIndex("dbo.HostingReportGroups", "UniqueCustomerAndLabel");
}
}
答案 0 :(得分:6)
C#字符串数据类型在T-SQL中被翻译为NVARCHAR(MAX)
。 SQL Server有限制:
聚合索引的最大允许大小为聚簇索引的900字节,非聚簇索引的最大允许大小为1,700。
大对象(LOB)数据类型ntext,text, varchar(max),nvarchar(max),varbinary(max),xml或image的列不能指定为键索引的列
所以你需要定义最大尺寸(使用注释):
[MaxLength(500)]
<强> DBFiddle Demo 强>