自定义字符串作为具有entity framework的主键

我正在尝试使用Code First Entity Framework将个性化字符串设置为主键。

我有一个帮助函数返回一个n-chars随机字符串,我想用它来定义我的Id,就像YouTubevideo代码一样。

using System.Security.Cryptography; namespace Networks.Helpers { public static string GenerateRandomString(int length = 12) { // return a random string } } 

我不想使用自动递增的整数(我不希望用户使用机器人太容易访问每个项目)或Guid(太长时间无法向用户显示)。

 using Networks.Helpers; using System; using System.ComponentModel.DataAnnotations; namespace Networks.Models { public class Student { [Key] // key should look like 3asvYyRGp63F public string Id { get; set; } public string Name { get; set; } } } 

是否可以定义如何在模型中直接分配Id? 我应该在模型中包含帮助程序的代码而不是使用外部类吗?

为了方便你的内部应用程序,我仍然使用int作为主键,但还包括唯一字符串索引的另一个属性:

 [Index(IsUnique=true)] [StringLegth(12)] public string UniqueStringKey {get;set;} 

字符串列必须是有限长度才能允许索引。

请记住,db将通过主键对记录进行物理排序,因此具有自动递增的int对于此是理想的 – 随机生成的字符串不是这样。

或者通过EF fluid api进行:

 modelBuilder.Entity() .Property(u => u.UniqueStringKey) .HasMaxLength(12) .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UQ_UniqueStringKey") { IsUnique = true }));