List null values are inserting null in the database

Anjali Agarwal 1,386 Reputation points
2023-01-31T00:47:07.1666667+00:00

Hello All,

I have the following two model classes:

public partial class EmployeeInfo

{

public int EmployeeInfoId { get; set; }

public string LastName { get; set; } = null!;

[DisplayName("First Name")]

public string FirstName { get; set; } = null!;

public virtual ICollection<EmergencyInfo> EmergencyInfos { get; } = new List<EmergencyInfo>();

}

public partial class EmergencyInfo

{

public int EmployeeInfoId { get; set; }

public string LastName { get; set; } = null!;

public string FirstName { get; set; } = null!;

public string EmailAddress { get; set; } = null!;

public virtual EmployeeInfo EmployeeInfo { get; set; } = null!;

}

The relationship between EmployeeInfo table and EmergencyInfo table is the foreign key EmployeeInfoId. The EmailAddress, FirstName, LastName are the required, non null fields in the database. There could only be maximum two emergency information so I have a loop that shows the input boxes for two emergency information. WhenI fill out one of the emergency information data and pass the valueto the controller. The List for both emergency Information comes to this method:

public async Task<IActionResult> Create(EmployeeInfo employeeInfo)

    {

        if (ModelState.IsValid)

        {

           await _employeeService.AddEmployee(employeeInfo);

            return RedirectToAction(nameof(Create));

        }

        return View(employeeInfo);

    }
Below is the screen shot. Now since I am only filling out the first emergency information, I pass NULL for second emergency info EmailAddress, FirstName, LastName and that throws an error saying, email address, FirstName and LastName is required because these three fields are required in the Database table. How can I avoid this? 


My second question is, I am prepopulating the fields of employeeInfo and employeeInfo
on my cshtml file. In order to acheive this, i am doing this:





  public async Task<IActionResult> Create()
   {
   
      employee = await _employeeService.GetEmployeeByEmployeeNumber(EmployeeId);
      return View(employee);
   }


 public async Task<EmployeeInfo?> GetEmployeeByEmployeeNumber(string employeeId)
   {
      var employee = await _ackContext.EmployeeInfos.OrderBy(e => e.EmployeeNumber).LastOrDefaultAsync(e => e.EmployeeNumber == employeeId);
       return employee;
   }


   This only populates my employeeInfo input boxes and ignores the emergencyInfo input boxes.
How can I modify my linq above so that employee can have both EmployeeInfo data and emergencyInfo data.
This is how my cshtml file looks like:



                
                    <label asp-for="LastName" class="control-label"></label>
                    <input asp-for="LastName" class="form-control input-lg" />
                    <span asp-validation-for="LastName" class="text-danger"></span>
                
                
                    <label asp-for="FirstName" class="control-label"></label>
                    <input asp-for="FirstName" class="form-control input-lg" />
                    <span asp-validation-for="FirstName" class="text-danger"></span>
                


  @for (var i = 0; i < 2; i++)
                { 
                
            
                        
                        <label asp-for="@Model.EmergencyInfos.ToList()[i].LastName" class="control-label"></label>
                        <input name="EmergencyInfos[@i].LastName" class="form-control" />
                        <span asp-validation-for="@Model.EmergencyInfos.ToList()[i].LastName" class="text-danger"></span>
                    
                        
                        <label asp-for="@Model.EmergencyInfos.ToList()[i].FirstName" class="control-label"></label>
                            <input name="EmergencyInfos[@i].FirstName" class="form-control" />
                            <span asp-validation-for="@Model.EmergencyInfos.ToList()[i].FirstName" class="text-danger"></span>
                    
					 
                            <label asp-for="@Model.EmergencyInfos.ToList()[i].EmailAddress" class="control-label"></label>
                            <input name="EmergencyInfos[@i].EmailAddress" class="form-control" />
                            <span asp-validation-for="@Model.EmergencyInfos.ToList()[i].EmailAddress" class="text-danger"></span>
                        
						
			}

 
        <input type="submit" value="Create" class="btn btn-primary" />
    
   

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,403 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,418 questions
C#
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.
10,650 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Johan Smarius 465 Reputation points MVP
    2023-08-26T15:38:50.5566667+00:00

    To answer your first question. Do not enter the second EmercencyInfo to the class if you do not have the information yet.

    Your LINQ query lacks an Include for the EmergencyInfo, so this information is not retrieved from the database. So to fix this so should either Include(EmergencyInfo) or add support for lazy loading.

    0 comments No comments