EF Core - unique, indexed, auto-generated guid column that is not the primary key

Viewed 7603

I am migrating from .NET EF to EF CORE. I have a working solution that automatically generates a unique GUID aside from its primary key. Below is the solution.

    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Index(IsUnique = true)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid TenantId { get; set; }

However, when i tried to migrate to EF Core, i am getting an error message when inserting the data: >SqlException: Cannot insert the value NULL into column 'TenantId', table 'DBContext.dbo.Tenants'; column does not allow nulls. INSERT fails. The statement has been terminated.

Here's my new code:

    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public Guid TenantId { get; set; }

Fluent:

    base.OnModelCreating(builder);
    builder.Entity<Tenant>()
     .HasIndex(t => t.TenantId)
     .IsUnique();
    builder.Entity<Tenant>()
     .Property(t => t.TenantId)
     .ValueGeneratedOnAdd();

This is inserted by using:

         _context.Tenants.Add(tenant);
        await _context.SaveChangesAsync();

Is this something that is not supported by EF Core and requires a workaround?

2 Answers

On your new code you don't have the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] annotation. Your code should be:

[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid TenantId { get; set; }

I think the reason why you are getting the Null is because you are supposed to instantiate the value of the Guid. something like

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid TenantId { get; set; } = Guid.NewGuid();
Related