marrrschine
marrrschine

Reputation: 632

How to create an entity with a Collection of another entity

As I am new to an ASP.NET Core 2.0 MVC I have a little demo app where I want to add a new entity of Type Lineup which has a ICollection of type Player in its model.

The involved classes are

public class Lineup
{
    public int LineupID { get; set; }
    public int PlayerID { get; set; }
    public ICollection<Player> Attendants { get; set; }
}

and

public class Player
{
    public int PlayerID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

My Create Lineup view looks like this

<form asp-action="Create">
    <div class="form-horizontal">
        <h4>Lineup</h4>
        <hr />
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Attendants" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="Attendants" class="form-control" 
                 asp-items="ViewBag.Players" multiple="multiple">
                </select>
            </div>
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>

The ViewBag.Players is part of the LineupsController:

private void PopulatePlayersDropDownList(object selectedPlayer = null)
{
    var playersQuery = from p in _context.Player
                           orderby p.Name
                           select p;
    ViewBag.Players = new SelectList(playersQuery.AsNoTracking(), "PlayerID",
                          "Name", selectedPlayer);
}

That's how it looks so far:

but inside my Create method

public async Task<IActionResult> Create([Bind("Attendants")] Lineup lineup)
{
    if (ModelState.IsValid)
    {
        _context.Add(lineup);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(lineup);
}

the Attendants count of the Lineup entity is 0 and not 2 as expected from the sample above. What is wrong here? Thanks for any help.

Upvotes: 0

Views: 118

Answers (2)

marrrschine
marrrschine

Reputation: 632

ok, these 2 steps solved my problem:

  1. see answer of krillgar
  2. changing the method signature of Create to

    public async Task Create(int[] PlayerIDs) { ... }

Upvotes: 0

krillgar
krillgar

Reputation: 12815

You need to instantiate your property when you create the object. Otherwise, the property is the default, which is null:

public class Lineup
{
    public int LineupID { get; set; }
    public int PlayerID { get; set; }
    public ICollection<Player> Attendants { get; set; } = new List<Player>();
}

Upvotes: 4

Related Questions