且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-15 10:56:52

除了将这些属性添加到您的 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.