Entity Framework Core 7 introduced a breaking change (although it is not listed in the breaking changes for EF Core 7): when defining model classes with scaffolding (Scaffold-DbContext
), EF Core 7 now makes the ICollection
properties read-only.
EF 6 code sample:
public virtual ICollection<PictureData> PictureData { get; set; }
public virtual ICollection<PictureMetaData> PictureMetaData { get; set; }
EF Core 7 code sample:
public virtual ICollection<PictureData> PictureData { get; } = new List<PictureData>();
public virtual ICollection<PictureMetaData> PictureMetaData { get; } = new List<PictureMetaData>();
I have code that assigns to these properties, is there any way to force the Scaffold-DbContext
to define these properties as not read-only? (And I don't want to change this manually...)
(And is there a reason for having these read-only?)
Thanks for any help!
You can customize the scaffolding since .NET 7 using Custom Reverse Engineering Templates. Install the required templates:
dotnet new install Microsoft.EntityFrameworkCore.Templates
Add them to your project (run from the project folder in terminal):
dotnet new ef-templates
Find CodeTemplates/EFCore/EntityType.t4
and modify all collection navigations to be settable (find all ICollection
mentions in the file). For example:
if (navigation.IsCollection)
{
#>
public virtual ICollection<<#= targetType #>> <#= navigation.Name #> { get; set; } = new List<<#= targetType #>>();
<#