`required` property and EF Core

375 views Asked by At

One year ago, in C# ver. 11, modifier required was added. So, if we mark property as required like below:

public class Point
{
    public required int X { get; set; }
    public required int Y { get; set; }
}

we can't create Point instance without init X and Y, so if we try:

        Point fake = new Point();

we get an compiler error:

Required member 'Point.X' must be set in the object initializer or attribute constructor.
Required member 'Point.Y' must be set in the object initializer or attribute constructor.

and the following code is ok:

Point point = new() { X = 1, Y = 2 };

Usually, this feature is necessary for parsing JSON (described here)

Ok. But let's look at EF Core. If we create entity model like this:

public class DownloadCenterFolder
{
    public int Id { get; set; }
    public string FolderName { get; set; }
}

we get a warning:

Non-nullable property 'FolderName' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

but if we mark it as required:

public class DownloadCenterFolder
{
    public int Id { get; set; }
    public required string FolderName { get; set; }
}

warning is disappeared

So, is it a good way to use required keyword for mandatory fields (which marked as builder.Property(p => p.ProjectName).IsRequired();) when we use EF Core or not? It looks like pretty (first at all, to avoid init this field by empty string in ctor) and I can't find anything in google about using this keyword with EF Core. Or, probably, any other way to mark mandatory fields?

Thanks

0

There are 0 answers