0

Is there any way to make autogenerated primary keys for string type, not int or guid?

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //???
    public string Id { get; set; } // string type

    public string Name { get; set; }
    public string Login { get; set; }
}

In case of following questions "why?": the thing is that in my current model PK is login, and I want to imperceptibly separate login and primary key, saving PKs that's already in use.

Serg Tomcat
  • 812
  • 10
  • 21
  • Login - is that a user name? I predict that one day someone will say "we don't like auto-generated logins, can we create our own?" Or "can we use email addresses to login instead?" Then you're going to have to fix up all those foreign keys.... – Colin Jun 24 '15 at 12:19
  • Exactly. At the moment the login IS the primary key. I want to make login as independent field, but save primary key as it is and generate PK for new users. Looks like manual generation is the only way. – Serg Tomcat Jun 24 '15 at 19:51
  • I think I would make `Id` an integer with identity, fix up all those foreign keys that are currently strings - it's a pain, but you've got to do some sort of fix up anyway. Then I would treat `Login` as the "natural" key, and validate as described here: http://stackoverflow.com/a/18736484/150342 – Colin Jun 25 '15 at 09:20

1 Answers1

1

Identities for string column types are not supported with SQL Server. How do you expect a custom key string to look like? You can do your key with Guid type and then fetch to string:

guid.ToString();
Alexander
  • 157
  • 1
  • 9