How to set NewId() for GUID in entity framework

后端 未结 7 1223
孤街浪徒
孤街浪徒 2020-12-06 01:43

I am creating asp.net mvc4 sample.In this i created Id column as GUID in Sample table of datacontext.

public class Sample
{
    [Required]
    public Guid          


        
7条回答
  •  情歌与酒
    2020-12-06 02:13

    When using Entity Framework Core 2.1.1 I use:

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

    Then in the migration, add in the defaultValueSql parameter as below:

    migrationBuilder.CreateTable(
        name: "Users",
        columns: table => new
        {
             UserId = table.Column(nullable: false, defaultValueSql: "newsequentialid()"),
             DisplayName = table.Column(nullable: true)
        },
           constraints: table =>
        {
            table.PrimaryKey("PK_Users", x => x.UserId);
        });
    

    This ensures that the sql server is responsible for generating a sequential guid which is going to be better than rolling your own.

    If you do not want the downsides of using sequential guids you can use "newid()" instead.

提交回复
热议问题