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;列不允许空值)
问题描述
我有一个主键为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";列不允许空值
基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01