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://docs.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]