Lehtonen M. Lehtonen M. - 1 year ago 113
C# Question

Custom string as Primary Key with Entity Framework

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 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 ?

Answer Source

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:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download