Create a Guide to Server Structure 4?

I come from an nhibernate background and I wonder how can I automatically generate Guid on the Serer side and not commit back and forth to make it on the database side?

In free nhibernate is just simple

Id(x => x.Id).GeneratedBy.GuidComb(); 
+9
guid entity-framework
Apr 30 '13 at 19:35
source share
3 answers

If you want to generate a key on the server, just do it in the code:

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

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

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

If you use sequential GUIDs, then there is no simple answer at the moment. Some examples that will help you on the right road:

+15
Apr 30 '13 at 23:20
source share

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; } } 

Testing 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")); } 
+1
May 01 '13 at 15:41
source share

As with EF 6.1.3, the default database values ​​[ newsequentialid() or newid() ] can be important when using a GUID as a PK. See the entity structure using guid as a primary key .

-one
May 29 '15 at 2:20
source share



All Articles