Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does EF Core DatabaseGeneratedOption.Computed work on GUID property

I have a Team entity that has a GUID TeamId property that I want to auto generate the values On Add when saving it to database (Note that property is NOT the primary key).

Am using EFCore 3.1.6 & the backend is SqlServer.

Based on the MS docs the value generation on Add depends on the database provider and it should be autogenerated for sql server - https://learn.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=data-annotations#value-generated-on-add. Now when I save a new Team, it fails because the TeamId wasn't auto generated but it is a Not Null field in the database.

Question: Shouldn't EFCore migrations setup default value for this TeamId field just by inferring it from the annotations? Or do I need to use HasDefaultValueSql("NewId()") in the OnModelCreating for this field?

If the HasDefaultValueSql("NewId()") was the missing piece then what is the point of the annotation?

public class Team
{
    public int Id { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public Guid TeamId { get; set; }

    [Required]
    public string Name { get; set; }
}

The table created by efcore database migration:

CREATE TABLE [dbo].[Teams](
    [Id] [INT] IDENTITY(1,1) NOT NULL,
    [TeamId] [UNIQUEIDENTIFIER] NOT NULL,
    [Name] [NVARCHAR](MAX) NOT NULL,
 CONSTRAINT [PK_Teams] PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
like image 858
Naren Avatar asked Sep 16 '25 03:09

Naren


1 Answers

Any of the following Fluent API statements will work in your case (non-PK and SQL Server):

entity.Property(e => e.TeamId)
    .HasValueGenerator<SequentialGuidValueGenerator>();

entity.Property(e => e.TeamId)
    .HasDefaultValueSql("(newsequentialid())");

entity.Property(e => e.TeamId)
    .HasDefaultValueSql("(newid())");

For a Guid property that is the primary key, the data annotation [DatabaseGenerated(DatabaseGeneratedOption.Identity)] and the Fluent API call .ValueGeneratedOnAdd() will work too. Both will use the SequentialGuidValueGenerator (not the default value).

like image 110
lauxjpn Avatar answered Sep 19 '25 08:09

lauxjpn