Custom string as Primary Key with Entity Framework

女生的网名这么多〃 提交于 2019-12-07 17:55:00

问题


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 ?


回答1:


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.




回答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 }));


来源:https://stackoverflow.com/questions/39663644/custom-string-as-primary-key-with-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!