Entity Framework 6 GUID 作为主键:无法将值 NULL 插入列“Id"、表“FileStore";列不允许空值

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column #39;Id#39;, table #39;FileStore#39;; column does not allow nulls(Entity Framework 6 GUID 作为主键:无法将值 NULL 插入列“Id、表“FileStore;列不允许空值)

本文介绍了Entity Framework 6 GUID 作为主键:无法将值 NULL 插入列“Id"、表“FileStore";列不允许空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主键为Id"的实体,它是 Guid:

I have an entity with primary key "Id" which is Guid:

public class FileStore
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Path { get; set; }
}

还有一些配置:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<FileStore>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    base.OnModelCreating(modelBuilder);
}

当我尝试插入记录时,出现以下错误:

When I try to insert a record I get a following error:

无法将值 NULL 插入到列Id"、表FileStore"中;列不允许空值.INSERT 失败. 语句已终止.

Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls. INSERT fails. The statement has been terminated.

我不想手动生成 Guid.我只想插入一条记录并获取 SQL Server 生成的 Id .如果我设置 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)Id 列不是 SQL Server 中的 Identity 列.

I don't want to generate Guid manually. I just want to insert a record and get Id generated by SQL Server. If I set .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity), Id column is not Identity column in SQL Server.

如何配置实体框架以在 SQL Server 中自动生成 Guid?

How can I configure Entity Framework to autogenerate Guid in SQL Server?

推荐答案

除了将这些属性添加到您的 Id 列之外:

In addition to adding these attributes to your Id column:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

在您的迁移中,您应该更改您的 CreateTable 以将 defaultValueSQL 属性添加到您的列,即:

in your migration you should change your CreateTable to add the defaultValueSQL property to your column i.e.:

Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"),

这将使您不必手动触摸数据库,正如您在评论中指出的那样,这是您希望通过 Code First 避免的事情.

This will prevent you from having to manually touch your database which, as you pointed out in the comments, is something you want to avoid with Code First.

这篇关于Entity Framework 6 GUID 作为主键:无法将值 NULL 插入列“Id"、表“FileStore";列不允许空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Entity Framework 6 GUID 作为主键:无法将值 NULL 插入列“Id"、表“FileStore";列不允许空值

基础教程推荐