Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Guid on Serverside Entity Framework 5?

I am coming from a nhibernate background and I am wondering how can I generate the Guid automatically on the serer side and not make a round trip to make it on the database side?

In fluent nhibernate it is simple just

   Id(x => x.Id).GeneratedBy.GuidComb();
like image 760
chobo2 Avatar asked Apr 30 '13 19:04

chobo2


2 Answers

If you want to generate the key on the server, simply do this in code:

public class TestObject 
{
    public TestObject() 
    {
        Id = Guid.NewGuid();
    }
    public Guid Id { get; set; }
}

If you want the database to generate the key, then use the DatabaseGenerated attribute:

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

If you're after using sequential GUIDs, then there's no easy answer at the moment. Some examples which get you along the right road:

  • Generating IDs in the SaveChanges method
  • Calling your own NewGuid method
  • Use a non-EF method to change the default value for the identity field from NEWID() to NEWSEQUENTIALID()
like image 185
Richard Avatar answered Nov 15 '22 00:11

Richard


This code does what you need:

using System;
using System.Runtime.InteropServices;
public static class SequentialGuidProvider
{
    [DllImport("rpcrt4.dll", SetLastError = true)]
    private static extern int UuidCreateSequential(out Guid guid);

    private static Guid CreateGuid()
    {
        Guid guid;
        int result = UuidCreateSequential(out guid);
        if (result == 0)
            return guid;
        else
            return Guid.NewGuid();
    }

    public static Guid GuidComb(this Nullable<Guid> guid)
    {
        if (!guid.HasValue) guid = SequentialGuidProvider.CreateGuid();
        return guid.Value;
    }
}

Test class:

public class TestObject
{
    public TestObject()
    {
    }

    private Nullable<Guid> _guid = null;
    public Guid Id
    {
        get
        {
            _guid = _guid.GuidComb();
            return _guid.Value();
        }
        set
        {
            _guid = value;
        }
    }
}

Test code:

    static void Main(string[] args)
    {
        TestObject testObject1 = new TestObject();
        TestObject testObject2 = new TestObject();
        TestObject testObject3 = new TestObject();
        //simulate EF setting the Id
        testObject3.Id = new Guid("ef2bb608-b3c4-11e2-8d9e-00262df6f594");

        //same object same id
        bool test1 = testObject1.Id == testObject1.Id;
        //different object different id
        bool test2 = testObject1.Id != testObject2.Id;
        //EF loaded object has the expected id
        bool test3 = testObject3.Id.Equals(new Guid("ef2bb608-b3c4-11e2-8d9e-00262df6f594"));
    }
like image 1
qujck Avatar answered Nov 14 '22 23:11

qujck