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]
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With