Reputation: 33
I'm trying to set a personalized string as Primary Key using Code First Entity Framework.
I have a helper with a function that returns a n-chars random string, and I want to use it to define my Id, as for YouTube video code.
using System.Security.Cryptography;
namespace Networks.Helpers
{
public static string GenerateRandomString(int length = 12)
{
// return a random string
}
}
I don't want to use auto-incremented integers (I don't want users using bots too easily to visit every item) nor Guid (too long to show to the users).
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; }
}
}
Is it possible to define how must the Id be assigned directly in the model ? Should I include the helper's code in the model instead of using an external class ?
Upvotes: 3
Views: 3437
Reputation: 2251
Or do it via EF fluid api:
modelBuilder.Entity<Student>()
.Property(u => u.UniqueStringKey)
.HasMaxLength(12)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UQ_UniqueStringKey") { IsUnique = true }));
Upvotes: 2
Reputation: 475
I'd still use a int as a primary key for convenience in your internal app, but also include another property for your unique string index:
[Index(IsUnique=true)]
[StringLegth(12)]
public string UniqueStringKey {get;set;}
The string column must be of finite length to allow an index.
Remember that the db will physically sort records by primary key, so having an automatically incrementing int is ideal for this - randomly generated strings not so.
Upvotes: 4