实体框架6 GUID作为主键:无法插入NULL值插入列'ID',表'FileStore的';列不允许空 [英] Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

查看:1053
本文介绍了实体框架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失败。\\ r \\ n此语句已终止。

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

我不想手动生成GUID。我只是想插入一条记录,并得到由SQL Server生成编号。如果我设置 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)编号列不在SQL服务器标识列。

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()"),

这将prevent您不必手动触摸你的数据库,你在评论中指出了,是要避免与code首先东西。

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.

这篇关于实体框架6 GUID作为主键:无法插入NULL值插入列'ID',表'FileStore的';列不允许空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆