Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set NewId() for GUID in entity framework

I am creating asp.net mvc4 sample.In this i created Id column as GUID in Sample table of datacontext.

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

This is entity table

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

Id pass 00000000-0000-0000-0000-000000000000.

How to set newid() to GUID and where i have to set.

like image 294
user2285613 Avatar asked Aug 13 '13 04:08

user2285613


2 Answers

I would recommend just using long for your ID type. It "just works" with and has some performance gains over GUID. But if you want to use a GUID, you should use a Sequential GUID and set it in the constructor. I would also make ID a private setter:

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

Sequential 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);
        }
    }
like image 158
Paul Avatar answered Oct 05 '22 12:10

Paul


If we ignore the politics around if this is a good idea or not, then the answer by @TombMedia is most likely what you are looking for.

If however, you need to add a new column to an existing table and want to specify newId() to be used for the default value because the field is not nullable then use this in your migration class:

AddColumn(
    "dbo.Samples",
    "UUID", 
    c => c.Guid(nullable: false, defaultValueSql: "newId()")
);

Note: this is an old question that is still relevant in EF6 and ranks high when looking for assistance on how to use newId inside EF migrations which is why this answer was added.

like image 22
Chris Schaller Avatar answered Oct 05 '22 11:10

Chris Schaller