9

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();
4

3 回答 3

18

如果要在服务器上生成密钥,只需在代码中执行此操作:

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 之后,那么目前没有简单的答案。一些让你走上正确道路的例子:

于 2013-04-30T23:20:52.133 回答
1

此代码可以满足您的需要:

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"));
    }
于 2013-05-01T15:41:22.683 回答
-1

从 EF 6.1.3 开始,在将 GUID 用作 PK 时,数据库默认值 [newsequentialid()newid()] 可能很重要。请参阅实体框架使用 guid 作为主键

于 2015-05-29T02:20:09.567 回答