我正在创建asp.net mvc4示例.在此我创建了ID列作为GUID在表格的datacontext.
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以及我必须设置的位置.
解决方法
我建议只使用长时间的ID类型.它与“GUID”相匹配,并具有一定的性能提升.但是,如果要使用GUID,您应该使用
Sequential GUID并将其设置在构造函数中.我也会将ID设为私人设定者:
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.Length - 4,4); return new Guid(buffer); } }