MarrionBerry
MarrionBerry

Reputation: 25

How to add related data in Entity Framework?

How to add related data in Entity Framework? What should be passed as parameters? I have the following code which doesn't work.

Model classes:

public class Department
{
    [Key]
    public int Id { get; set; }

    [Required]
    [DisplayName("Department Name")]
    public string Name { get; set; }
}

public class Equipment
{
    [Key]
    public int Id { get; set; }

    [Required]
    [DisplayName("Equipment Name")]
    public string Name { get; set; }

    [Required]
    public int Amount { get; set; }

    [Required]
    public string Status { get; set; }
    public int DepartmentId { get; set; }
    public Department Department { get; set; }

}

Create Action Method in EquipmentController.cs:

// GET: Equipment/Create
public IActionResult Create()
{
    ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "Name");
    return View();
}

// POST: Equipment/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Amount,Status,DepartmentId")] Equipment equipment)
{
    if (ModelState.IsValid)
    {
        _context.Add(equipment);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "Name", equipment.DepartmentId);
    return View(equipment);
}

View:

@model Equipment

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Equipment</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Amount" class="control-label"></label>
                <input asp-for="Amount" class="form-control" />
                <span asp-validation-for="Amount" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Status" class="control-label"></label>
                <input asp-for="Status" class="form-control" />
                <span asp-validation-for="Status" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DepartmentId" class="control-label"></label>
                <select asp-for="DepartmentId" class ="form-control" asp-items="ViewBag.DepartmentId"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

The data being passed in the debugger: values in debugger

When I click the Create button the data won't be saved into the database. I want to be able to add equipments with a DepartmentId linked to them and also being to print out equipments with their department names.

Upvotes: 0

Views: 210

Answers (1)

Qing Guo
Qing Guo

Reputation: 9112

I know what you mean, could you try the below model to create a new project?

Department:

  public class Department
    {
    [Key]
    public int Id { get; set; }

    [Required]
    [DisplayName("Department Name")]
    public string Name { get; set; }
    public ICollection<Equipment>? Equipment { get; set; }
    }

Equipment

 public class Equipment
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [DisplayName("Equipment Name")]
        public string Name { get; set; }

        [Required]
        public int Amount { get; set; }

        [Required]
        public string Status { get; set; }
        [ForeignKey("DepartmentId")]
        public int DepartmentId { get; set; }
        public Department Department { get; set; }

    }

In asp.net core6 remove below line from the project.csproj:

 <Nullable>enable</Nullable>

result:

enter image description here

Upvotes: 1

Related Questions