How to use the required modifier in C# properties correctly?

Goverdhan Jayaram 40 Reputation points
2024-01-15T06:46:19.88+00:00
public class State
{
    public int StateId { get; set; }

    public required string StateName { get; set; }

    public required ICollection<District> Districts { get; set; }


    public static void CreateNewState()
    {

        State state = new State(); 

    }
}

I am using Entity Framework Core.

I want to create a 'New State'.

I get the errors below.

Required member state.StateName must be set in the object initiailzer or attribute constructor.
Required member state.Districts must be set in the object initializer or attribute constructor.

I am looking for guidance to use the required modifier correctly.  I am not able to understand how to use the object initializer or attribute constructor.
Developer technologies | .NET | Entity Framework Core
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Viorel 125.7K Reputation points
    2024-01-15T06:58:46.48+00:00

    This initialization should solve the compilation errors:

    public static void CreateNewState( )
    {
        State state = new State { StateName = "some name", Districts = new List<District>( ) };
    
    
    }
    

    You can also set the StateId and add items to Districts.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 82,061 Reputation points Volunteer Moderator
    2024-01-16T02:24:53.9333333+00:00

    The required keyword is unrelated to entity framework. It marks a property / field needs it value set during construction. If you want a field required with EF you use the [Required] attribute.

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.