使用实体框架将自定义字符串作为主键 [英] Custom string as Primary Key with Entity Framework

查看:67
本文介绍了使用实体框架将自定义字符串作为主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to set a personalized string as Primary Key using Code First Entity Framework.

我有一个带有返回n字符随机字符串的函数的助手,我想用它来定义我的ID,就像YouTube视频代码一样.

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

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

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; }
    }
}

是否可以定义必须在模型中直接分配ID的方式? 我应该在模型中包括帮助程序的代码,而不是使用外部类吗?

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 ?

推荐答案

在内部应用程序中,为了方便起见,我仍将int用作主键,但还要为唯一的字符串索引包括另一个属性:

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.

请记住,数据库将按主键对记录进行物理排序,因此对此具有自动递增的int是理想的-随机生成的字符串并非如此.

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.

这篇关于使用实体框架将自定义字符串作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆