在服务器端实体框架5上生成Guid?

时间:2013-04-30 19:35:56

标签: entity-framework guid

我来自nhibernate背景,我想知道如何在serer端自动生成Guid而不是在数据库端进行往返?

在流利的nhibernate中,它很简单

   Id(x => x.Id).GeneratedBy.GuidComb();

3 个答案:

答案 0 :(得分:17)

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

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,那么目前没有简单的答案。一些可以帮助您走上正确道路的例子:

答案 1 :(得分: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"));
    }

答案 2 :(得分:-1)

从EF 6.1.3开始,当使用GUID作为PK时,数据库默认值[newsequentialid()newid()]可能很重要 见entity framework use a guid as the primary key