I have Main Model class as Bellow
public class MainModel
{
public string Code{ get; set; }
public string FullName{ get; set; }
public string Position{ get; set; }
public virtual SUB_DETAILS subdetails { get; set; }
}
and SUB_DETAILS Model class is:
public class SUB_DETAILS
{
public SUB_DETAILS()
{
MainModel= new HashSet<MainModel>();
}
public string UniqueCode { get; set; }
public string PassportNumber { get; set; }
public virtual ICollection<MainModel> MainModel{ get; set; }
}
I want to set values to these models to send data to Web API myCode is:
MainModel r = new MainModel();
r.Code= "1245454354";
r.FullName= "FullName Here";
r.Position="Position Here";
r.subdetails.UniqueCode="151221";
r.subdetails.PassportNumber="2145";
var sendData = client.PostAsJsonAsync("api/PostData", new List<MainModel> { r }).Result;
it doest not accept value for r.subdetails.UniqueCode="151221";
and r.subdetails.PassportNumber="2145";
and give me the Error "Object reference not set to an instance of an object. MainModel.subdetails.get return null" can anyone help how to set value for my MainModel and it's SUB_DETAILS to send Correct data to Web API
CodePudding user response:
it's wrong You can change this
SUB_DETAILS s = new SUB_DETAILS();
s.MainModel.Add(
new MainModel
{
Code = "1245454354",
FullName = "FullName Here",
Position = "Position Here"
}
);
s.UniqueCode = "151221";
s.PassportNumber = "2145";
var sendData = client.PostAsJsonAsync("api/PostData", new List<SUB_DETAILS> { s }).Result;
public class MainModel
{
public string Code { get; set; }
public string FullName { get; set; }
public string Position { get; set; }
}
public class SUB_DETAILS
{
public SUB_DETAILS()
{
MainModel = new HashSet<MainModel>();
}
public string UniqueCode { get; set; }
public string PassportNumber { get; set; }
public virtual ICollection<MainModel> MainModel { get; set; }
}
CodePudding user response:
Or
MainModel r = new MainModel();
r.Code = "1245454354";
r.FullName = "FullName Here";
r.Position = "Position Here";
r.SUB_DETAILS.Add(new SUB_DETAILS
{
UniqueCode = "151221",
PassportNumber= "2145"
});
var sendData = client.PostAsJsonAsync("api/PostData", new List<MainModel> { r }).Result;
public class MainModel
{
public MainModel()
{
SUB_DETAILS = new HashSet<SUB_DETAILS>();
}
public string Code { get; set; }
public string FullName { get; set; }
public string Position { get; set; }
public virtual ICollection<SUB_DETAILS> SUB_DETAILS { get; set; }
}
public class SUB_DETAILS
{
public string UniqueCode { get; set; }
public string PassportNumber { get; set; }
}