How to handle this error in C# "Required Member must be set in object initiialzer or attribute constructor"

541 Views Asked by At

I have two classes - State - Principal Class and District Dependant class.

public class State
{
    public int StateId { get; set; }

    public required string StateName { get; set; }

    public 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.

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.

I have tried to understand how to use the required modifier in the properties of a class. I am unable to understand the concepts.

1

There are 1 best solutions below

1
SeekerOfKnowledge On

I used the knowledge and directions given by Shingo and Jon and found the answer. Thank you everyone!

public static void CreateState()
 {

     State state = new State() { StateName = "Karnataka" };

     RMIDbContext db = new RMIDbContext();

     db.States.Add(state);
     db.SaveChanges();

 }