Guid 为空,首先是 newsequentialid() 和 EF 数据库

Guid is empty with newsequentialid() and EF database first

我正在开发一个首先使用 EF 4.1 和数据库的网站。 我也在使用 aspnet tables,特别是 aspnet_Users,它使用 Guid 作为主键。 因此,我的自定义用户 table 也有一个 Guid 作为主键,它是 aspnet_Users id 的外键。

最近,我读到使用 Guid 作为主键是个坏主意,除非使用 newsequentialid()

使用 Sql Server Management Studio 我已将所有主键的默认值更新为 newsequentialid(),并在我的 edmx 设计器中将 StoreGeneratedPattern 设置为 Identity

但是,每当我尝试添加一个对象(例如 Item 具有 Guid 主键)时,它在数据库中的 ID 仍然为空(全为 0)。

public void CreateItem()
{
    using (var uof = new UnitOfWork())
    {
        Item item = new Item();
        itemRepo.Add(item);
        uof.Commit();
    }
}

以及添加方法:

public class RepositoryBase<TObject> where TObject : IEntity
{
    protected CavalenaEntities entities
    {
        get { return UnitOfWork.Current.Context; }
    }

    public void Add(TObject entity)
    {
        entities.Entry(entity).State = System.Data.EntityState.Added;
    }
}

我是不是忘记了什么? 虽然我为我的数据库的主键设置了默认值,但它们在 edmx 设计器中的 Default Value 属性 仍然是 None。正常吗?

另一个解决方案是使用 int 作为主键而不是 Guid 但是我怎么能在我的自定义用户 table 和 aspnet_Users 之间做 link,它使用 Guid ?

非常感谢!

除非您需要序列标识符,否则使用 NEWID() 绝对可以。但是你可能不需要 Guid/uniqueidentifier,你可以使用 intbigint 和身份或 SQL 序列对象。

在模型设计器中获取主键的属性。 找到 StoreGeneratedPattern 并将其从 None 更改为 Identity。 保存所有内容,现在主键将正确生成。