MVC Identity 2.2.1 - Primary Key (Guid) as UniqueI

2019-07-14 04:49发布

问题:

Current project:

  • ASP.NET 4.5.2
  • MVC 5
  • Identity 2.2.1

One of the problems I am running into is that I am making use of GUIDs properly throughout the rest of the project, with the DB field types being UniqueIdentifier. Unfortunately, Identity does not play by the same rules, and for some inscrutable reason they created the table fields as a string -- nVarChar(128).

I have found a few hits out there that show how to properly modify Identity to use UniqueIdentifier and cast the Guids to the proper format, however all these resources are currently obsolete - most are for pre-v2 and the most recent one was for 2.0.0-alpha, and the code it provided doesn’t match up or work on the current version of Identity.

I have done my best to Google what is out there, but either it doesn’t exist or my Google-fu is weak today. I am looking for any pointers on how to change the DB field to a UniqueIdentifier (as proper for a Guid) while still have everything else work/cast properly.

EDIT: It seems that a person or system has linked this article as a possible duplicate to another article. Problem is, I already linked to that other article as being a v1.x usage of Identity, and as such, not directly applicable. Even the 2.0.0-alpha code that I linked to does not work. Even the additional material at the bottom of the linked article is not functional under 2.2.1.

回答1:

Maybe this will help:

Entity Framework – Use a Guid as the primary key

UPDATE So if you will use GUID like this:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

EF will generate uniqueidentifier in your DB table, but it's important that column value to be set to (newsequentialid()) and make StoreGeneratedPattern to Identity. So this will automaticaly generate next unique ID

using (ApplicationDbContext context = new ApplicationDbContext())
{
    var item = new Item
                 {
                     Name = "Random",
                     Description= "Person";
                 };

    context.Items.Add(item);
    context.SaveChanges();
    Console.WriteLine(item.Id);
}

Home this will helpfull.