Linq query and violation of inserting null in database

Anjali Agarwal 1,386 Reputation points
2023-01-31T01:42:14.5866667+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 value

to 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 for both the list values. 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. How can I avoid this?

User's image

Below is the screen shot for the second list item that doesnt have any value and it is passing NULL to the database and I get an exception that NULL value is not allowed in the Database:

User's image

My second question is, I am prepopulating the fields of employeeInfo

on my cshtml file. In order to achieve 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:

<div class="form-group row">

            <div class="col-sm-4">

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

            </div>

            <div class="col-sm-4">

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

            </div>

</div>

@for (var i = 0; i < 2; i++)

            { 

            <div class="form-group row">

        

                    <div class="col">

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

                </div>

                    <div class="col">

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

                </div>

				 <div class="col">

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

                    </div>

					</div>

		}

<div class="form-group">

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

</div>

any help will be greatly appreciated.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,207 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,288 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,307 questions
{count} votes

Accepted answer
  1. Xinran Shen - MSFT 2,091 Reputation points
    2023-02-01T08:38:24.66+00:00

    HI, @Anjali Agarwal, From your question, Here is a simple demo about how to achieve it. Hope it can give you some help.

    Model:

    public class ModelB
        {
            public string Name { get; set; }
            public List<ModelA> modelAs { get; set; } = new List<ModelA>();
        }
    
    public class ModelA
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    

    View:

    enter image description here

    Full code: A.txt

    In this case, when the page load, I hide the send item and disable the input tag, So when user click the submit button, It will only submit the first item, But when user click the add new item , Page will show the second item. If use don't input any value into input tag, the project will not allow the form to be send to the backend and show error message in client side. So where will not be any null value inserted into db.

    Demo:

    2321


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Xinran Shen

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful