我来自于一个 nhibernate 背景,想知道如何在服务器端自动生成 Guid,而不必在数据库端进行往返操作?
在 fluent nhibernate 中,只需简单地执行以下操作:
Id(x => x.Id).GeneratedBy.GuidComb();
我来自于一个 nhibernate 背景,想知道如何在服务器端自动生成 Guid,而不必在数据库端进行往返操作?
在 fluent nhibernate 中,只需简单地执行以下操作:
Id(x => x.Id).GeneratedBy.GuidComb();
public class TestObject
{
public TestObject()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
}
如果你希望数据库生成密钥,则可以使用DatabaseGenerated 属性:public class TestObject
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
}
如果你想使用连续的GUID,那么目前没有简单的答案。以下是一些能够指导你正确方向的示例:
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"));
}
从EF 6.1.3开始,当使用GUID作为主键时,数据库默认值[newsequentialid()
或newid()
]可能非常重要。请参见entity framework use a guid as the primary key。