Database first scaffold doesn't generate StringLength attribute for char fields
See original GitHub issueHi there,
I’m generating my EF Core model from a Postgres database and I noticed that varchar fields receive the StringLength attribute but char(…) fields don’t. Is there a way to configure this so that they receive the StringLength attribute as well? I’m using the attributes for validation in my REST API so having the attribute generated would be helpful to prevent invalid values throwing an exception on insert.
The relevant columns in the database:
Column | Type | Modifiers |
---|---|---|
translation | character varying(100) | not null |
dflt_station | character(8) |
And the relevant parts of the model:
[Required]
[StringLength(100)]
public string Translation { get; set; }
[Column("dflt_station", TypeName = "character(8)")]
public string DfltStation { get; set; }
As you can see the char column receives the TypeName attribute instead of StringLength. The model is being generated with the command:
Scaffold-DbContext "..." Npgsql.EntityFrameworkCore.PostgreSQL -o Models -Context "..." -ContextDir Database -f -d
This is occurring with Dotnet Core 2.2, Npgsql.EntityFrameworkCore.PostgreSQL 2.2, and EntityFramework 6.2.0
I’m not sure if this is on your side or on EF Core so sorry for the trouble. Thanks!
Issue Analytics
- State:
- Created 5 years ago
- Comments:10 (4 by maintainers)
@roji - That indeed a bug. Basically, we are supposed to pass in the default value for the facet and see if the typemapping sets the facet as what we got from server. Hence we don’t need to scaffold. For Unicode default is true, for size default is null, for fixed length default is … false.
@smitpatel I dove into it a little and I think there’s an issue on the EF Core side…
In ScaffoldingTypeMapper, there’s a section that tries to find out whether fixedLength=true is the default, inferred setting - if it is there’s no need to specify it explicitly on the scaffolded model:
The part I don’t understand is where
fixedLength
is true in this call - if you pass in a RelationalTypeMappingInfo withfixedLength
true, then obviously you’ll get back a mapping with the same, and assume that it’s the default and does not need to be scaffolded.Compare this with the check for
maxLength
just below, where the length isn’t passed into the check. In that case, if the length on the returned mapping is equal to the one specified, that indeed means it can be omitted from the scaffolded model.Note that the same issue seems to exist with the unicode check above. Assuming I haven’t totally misunderstood this code, I can submit a fix.
/cc @bricelam @ajcvickers