Custom string as Primary Key with Entity Framework
Asked Answered
D

2

3

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 ?

Diaconicum answered 23/9, 2016 at 14:46 Comment(5)
Out of curiosity, why use a custom, randomly generated string, if a GUID is (approximately) the same?Brunner
You are putting your code in risk, there is possibility to get 2 same random stringsZimmermann
@Bwolfing The main reason is that I wanted something more user-friendly. A Guid, even when converted to base64, is still 22 characters long. For example if you want to include a link to your profile on a forum, a shorter one looks better.Diaconicum
@HadiHassan I thought of that and I planned a verification to be sure the generated string was not in use.Diaconicum
@LehtonenM. Makes sense! I always opt for integers, since the search and comparisons are fundamentally easier/faster, but strings provide a more user-friendly experience and appearance in ways :)Brunner
T
4

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.

Touraco answered 23/9, 2016 at 14:52 Comment(1)
This looks like a good alternative to my problem, i will use it on my project.Diaconicum
I
2

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 }));
Isobaric answered 23/9, 2016 at 15:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.