此代码可以满足您的需要:
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;
}
}
测试类:
public class TestObject
{
public TestObject()
{
}
private Nullable<Guid> _guid = null;
public Guid Id
{
get
{
_guid = _guid.GuidComb();
return _guid.Value();
}
set
{
_guid = value;
}
}
}
测试代码:
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"));
}