Asp.net-Mvc

如何在實體框架中為 GUID 設置 NewId()

  • December 11, 2018

我正在創建 asp.net mvc4 範例。在此我在 datacontext 的範例表中創建了 Id 列作為 GUID。

public class Sample
{
   [Required]
   public Guid ID { get; set; }
   [Required]
   public string FirstName { get; set; }
}

這是實體表

CreateTable(
"dbo.Samples",
c => new
{
    ID = c.Guid(nullable: false),
    FirstName = c.String(nullable: false)                   
})
.PrimaryKey(t => t.ID);

ID通過00000000-0000-0000-0000-000000000000。

如何設置newid()以及GUID我必須設置的位置。

我建議僅long用於您的 ID 類型。它與 GUID 一起“正常工作”並在性能上有所提升。但是如果你想使用 GUID,你應該使用順序 GUID並在建構子中設置它。我也會讓 ID 成為private二傳手:

public class Sample
{
   public Sample() {
       ID = GuidComb.Generate();
   }
   [Required]
   public Guid ID { get; private set; }
   [Required]
   public string FirstName { get; set; }
}

順序 GUID

public static class GuidComb
   {
       public static Guid Generate()
       {
           var buffer = Guid.NewGuid().ToByteArray();

           var time = new DateTime(0x76c, 1, 1);
           var now = DateTime.Now;
           var span = new TimeSpan(now.Ticks - time.Ticks);
           var timeOfDay = now.TimeOfDay;

           var bytes = BitConverter.GetBytes(span.Days);
           var array = BitConverter.GetBytes(
               (long)(timeOfDay.TotalMilliseconds / 3.333333));

           Array.Reverse(bytes);
           Array.Reverse(array);
           Array.Copy(bytes, bytes.Length - 2, buffer, buffer.Length - 6, 2);
           Array.Copy(array, array.Length - 4, buffer, buffer.Length - 4, 4);

           return new Guid(buffer);
       }
   }

引用自:https://stackoverflow.com/questions/18200817