Custom string as Primary Key with Entity Framework

怎甘沉沦 提交于 2019-12-06 02:47:28

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.

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