Entity Framework - 字符串列的唯一约束
Entity Framework - Unique constraint on a string column
我是 EF (6.2) 的初学者,我正在尝试使用代码优先方法生成数据库。
我的一些实体有一个字符串 属性,它应该是唯一的,例如用户名或文章标题。
为了确保唯一性,我添加了一个索引,指定该列应该是唯一的:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Blog.Models
{
public class User
{
[Key, Index, Required]
public int Id { get; set; }
[Index(IsUnique = true), Required]
public string Name { get; set; }
[Required]
public string Password { get; set; }
public ICollection<Comment> Comments { get; set; }
}
}
但是它会抱怨,因为我试图在字符串类型列上添加索引,而它接受在整数列(例如行 ID)上使用索引。
我可以使用 Key
属性,但我已经在使用它来定义主键并且我不希望 EF 相信我希望该名称是复合主键的组成部分键,也不会将其视为实际的主键。
所以我的问题是:为什么不能在字符串类型的列上添加索引,如何确保给定列的唯一性(唯一性?)?谢谢。
如 MSDN 的教程中所写,Indexes
可以在 strings
上实现,正如它们在以下示例代码中所述
public class User
{
public int UserId { get; set; }
[Index(IsUnique = true)]
[StringLength(200)]
public string Username { get; set; }
public string DisplayName { get; set; }
}
但是说到多列索引,他们提到你需要写顺序。
可能会发生冲突,因为您在 Id
上使用了没有任何名称的 Index
,并且在 Name
上使用了没有任何名称的 Index
。尝试为 Name
的 Index
定义一个名称。我不确定这是否有效,但值得一试。
可以在 MSDN website 找到更多信息。
我是 EF (6.2) 的初学者,我正在尝试使用代码优先方法生成数据库。
我的一些实体有一个字符串 属性,它应该是唯一的,例如用户名或文章标题。
为了确保唯一性,我添加了一个索引,指定该列应该是唯一的:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Blog.Models
{
public class User
{
[Key, Index, Required]
public int Id { get; set; }
[Index(IsUnique = true), Required]
public string Name { get; set; }
[Required]
public string Password { get; set; }
public ICollection<Comment> Comments { get; set; }
}
}
但是它会抱怨,因为我试图在字符串类型列上添加索引,而它接受在整数列(例如行 ID)上使用索引。
我可以使用 Key
属性,但我已经在使用它来定义主键并且我不希望 EF 相信我希望该名称是复合主键的组成部分键,也不会将其视为实际的主键。
所以我的问题是:为什么不能在字符串类型的列上添加索引,如何确保给定列的唯一性(唯一性?)?谢谢。
如 MSDN 的教程中所写,Indexes
可以在 strings
上实现,正如它们在以下示例代码中所述
public class User
{
public int UserId { get; set; }
[Index(IsUnique = true)]
[StringLength(200)]
public string Username { get; set; }
public string DisplayName { get; set; }
}
但是说到多列索引,他们提到你需要写顺序。
可能会发生冲突,因为您在 Id
上使用了没有任何名称的 Index
,并且在 Name
上使用了没有任何名称的 Index
。尝试为 Name
的 Index
定义一个名称。我不确定这是否有效,但值得一试。
可以在 MSDN website 找到更多信息。